“方法重载”在Python中

发布于 2024-11-18 21:19:47 字数 374 浏览 0 评论 0原文

我认为这个概念叫做重载。 现在我正在编写一个提供 getter 和 setter 方法的类,但遇到了一个设计问题。

这两种方法都是简单的方法,只是设置一个值或返回一个值。

def set_number(self, num):

   self.count = num

def get_number(self):

   return self.count

通过做一些基本上将两种方法合二为一的事情,然后根据是否提供 num 参数来决定应该执行哪一行,是否会更好地节省空间并使类“看起来”更小?

或者我应该坚持清晰度并将它们分开?有些人认为将所有这些俏皮话单独保留是“浪费空间”,而另一些人则不同意并宁愿将它们分开。

我有什么理由选择其中之一?

I think the concept is called overloading.
Right now I'm writing a class that will provide getter and setter methods, and am stuck on a design issue.

Both methods are one-liners that simply set a value, or return a value.

def set_number(self, num):

   self.count = num

def get_number(self):

   return self.count

Would it be better to save space and make the class "look" smaller by doing something that will basically combine the two methods into one and then just decide which line should be executed depending on whether the num argument is provided?

Or should I just stick to clarity and keep them separated? Some people feel that it's a "waste of space" to keep all these one-liners on their own, while others disagree and prefer splitting them up.

Any reasons why I would choose one or the other?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

云胡 2024-11-25 21:19:47

在 Python 中,您应该根本不使用 getter 和 setter。相反,只需直接引用 count 属性,例如 print instance.countinstance.count = 5

其他语言中 getter 和 setter 的要点是用于封装和面向未来,以防您需要向 getter 或 setter 添加逻辑。在 Python 中,您可以稍后使用 property 来完成此操作,这不会破坏您现有的 API。

@property
def number(self):
     # do extra logic if necessary
    return self.count

属性也可以有设置器 - 请参阅:http://docs.python.org/library/functions .html#property

Python 不是 Java。 =)

额外奖励阅读材料:

In Python, you should prefer not to use getters and setters at all. Instead simply reference the count attribute directly, e.g. print instance.count or instance.count = 5

The point of getters and setters in other languages is for encapsulation and for future-proofing in case you need to add logic to the getters or setters. In Python you can accomplish this by later using property, which will not break your existing API.

@property
def number(self):
     # do extra logic if necessary
    return self.count

Properties can also have setters - see: http://docs.python.org/library/functions.html#property

Python is not Java. =)

Extra bonus reading material:

捂风挽笑 2024-11-25 21:19:47

一般来说,在 python 中使用显式的 getter/setter 方法是非常糟糕的风格。只需执行以下操作:

In [1]: class Foo(object):
   ...:     def __init__(self):
   ...:         self.num = 1
   ...:         
   ...:         
In [2]: f = Foo()
In [3]: f.num
Out[3]: 1
In [4]: f.num = 2
In [5]: f.num
Out[5]: 2

如果您确实需要逻辑,则可以在以后使用 属性。请注意下面如何保留相同的接口,同时仍然添加功能。

In [8]: class Foo(object):
   ...:     def __init__(self):
   ...:         self._num = 1
   ...:     @property
   ...:     def num(self):
   ...:         return self._num
   ...:     @num.setter
   ...:     def num(self, num):
   ...:         if num < 0:
   ...:             raise ValueError("Your Foo would be too small!")
   ...:         self._num = num
   ...:         
   ...:         
In [10]: f = Foo()
In [11]: f.num
Out[11]: 1
In [12]: f.num = 2
In [13]: f.num
Out[13]: 2
In [14]: f.num = -1
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)

/home/Daenyth/<ipython console> in <module>()

/home/Daenyth/<ipython console> in num(self, num)

ValueError: Your Foo would be too small!

关于“超载”——该术语不适用于此处。该术语用于通过更改对象上这些方法的定义来更改 +== 等运算符的行为。您可以通过 __cmp__ 在 python 中进行一些重载, __add__,依此类推。

Generally in python it's very bad style to use explicit getter/setter methods. Just do something like this:

In [1]: class Foo(object):
   ...:     def __init__(self):
   ...:         self.num = 1
   ...:         
   ...:         
In [2]: f = Foo()
In [3]: f.num
Out[3]: 1
In [4]: f.num = 2
In [5]: f.num
Out[5]: 2

If you really need logic, you can preserve this same API at a later date by using properties. Notice how the same interface is preserved below while still adding functionality.

In [8]: class Foo(object):
   ...:     def __init__(self):
   ...:         self._num = 1
   ...:     @property
   ...:     def num(self):
   ...:         return self._num
   ...:     @num.setter
   ...:     def num(self, num):
   ...:         if num < 0:
   ...:             raise ValueError("Your Foo would be too small!")
   ...:         self._num = num
   ...:         
   ...:         
In [10]: f = Foo()
In [11]: f.num
Out[11]: 1
In [12]: f.num = 2
In [13]: f.num
Out[13]: 2
In [14]: f.num = -1
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)

/home/Daenyth/<ipython console> in <module>()

/home/Daenyth/<ipython console> in num(self, num)

ValueError: Your Foo would be too small!

Regarding "overloading" -- That term does not apply here. That is the term for changing the behavior of operators like +, ==, and so on, by changing the definition for those methods on your object. You can do some overloading in python via __cmp__, __add__, and so on.

风启觞 2024-11-25 21:19:47

为了代码的可读性和可维护性,我将其保留为两个单独的方法。

I would leave it as two separate methods for the sake of code readabilty and maintainabilty.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文