你使用 get/set 模式(在 Python 中)吗?

发布于 2024-08-28 06:19:07 字数 108 浏览 15 评论 0原文

使用 get/set 似乎是 Java 中的常见做法(出于各种原因),但我几乎没有看到使用此方法的 Python 代码。

为什么在 Python 中使用或避免使用 get/set 方法?

Using get/set seems to be a common practice in Java (for various reasons), but I hardly see Python code that uses this.

Why do you use or avoid get/set methods in Python?

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

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

发布评论

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

评论(8

七婞 2024-09-04 06:19:07

在 python 中,您可以直接访问该属性,因为它是公共的:

class MyClass:

    def __init__(self):
        self.my_attribute = 0  

my_object = MyClass()
my_object.my_attribute = 1 # etc.

如果您想对属性的访问或更改执行某些操作,可以使用 properties

class MyClass:

    def __init__(self):
        self._my_attribute = 0

    @property
    def my_attribute(self):
        # Do something if you want
        return self._my_attribute

    @my_attribute.setter
    def my_attribute(self, value):
        # Do something if you want
        self._my_attribute = value

至关重要的是,客户端代码保持不变。

In python, you can just access the attribute directly because it is public:

class MyClass:

    def __init__(self):
        self.my_attribute = 0  

my_object = MyClass()
my_object.my_attribute = 1 # etc.

If you want to do something on access or mutation of the attribute, you can use properties:

class MyClass:

    def __init__(self):
        self._my_attribute = 0

    @property
    def my_attribute(self):
        # Do something if you want
        return self._my_attribute

    @my_attribute.setter
    def my_attribute(self, value):
        # Do something if you want
        self._my_attribute = value

Crucially, the client code remains the same.

掐死时间 2024-09-04 06:19:07

很酷的链接:Python 不是 Java :)

在 Java 中,您必须使用 getter 和 setter,因为使用公共字段使您没有机会在以后返回并改变主意以使用 getter 和 setter。因此,在 Java 中,您不妨预先解决掉这些杂务。在 Python 中,这是愚蠢的,因为您可以从普通属性开始并随时改变主意,而不会影响该类的任何客户端。因此,不要编写 getter 和 setter。

Cool link: Python is not Java :)

In Java, you have to use getters and setters because using public fields gives you no opportunity to go back and change your mind later to using getters and setters. So in Java, you might as well get the chore out of the way up front. In Python, this is silly, because you can start with a normal attribute and change your mind at any time, without affecting any clients of the class. So, don't write getters and setters.

つ低調成傷 2024-09-04 06:19:07

以下是 Guido van Rossum 在编程大师< /a>

“对抗语言”是什么意思?

Guido:这通常意味着他们
试图继续他们的习惯
使用不同的语言效果很好。

[...]人们会把一切变成
一个类,并将每个访问变成一个
访问器方法,
在 Python 中这确实不是明智之举;
你会得到更详细的代码
更难调试并且运行速度慢很多。
你知道这句话“你可以写
FORTRAN 可以用任何语言编写吗?”您也可以用任何语言编写 Java。

Here is what Guido van Rossum says about that in Masterminds of Programming

What do you mean by "fighting the language"?

Guido: That usually means that they're
trying to continue their habits that
worked well with a different language.

[...] People will turn everything into
a class, and turn every access into an
accessor method,
where that is really not a wise thing to do in Python;
you'll have more verbose code that is
harder to debug and runs a lot slower.
You know the expression "You can write
FORTRAN in any language?" You can write Java in any language, too.

紙鸢 2024-09-04 06:19:07

不,它不是Pythonic的。普遍接受的方法是使用普通数据属性,并用属性替换需要更复杂的获取/设置逻辑的属性。

No, it's unpythonic. The generally accepted way is to use normal data attribute and replace the ones that need more complex get/set logic with properties.

擦肩而过的背影 2024-09-04 06:19:07

对您问题的简短回答是否定的,您应该在需要时使用属性。 Ryan Tamyoko 在他的文章 Getters/Setters/Fuxors 中提供了详细的答案

从这一切中获得的基本价值是,您要努力确保每一行代码对程序员都有一定的价值或意义。编程语言是为人类服务的,而不是为机器服务的。如果您的代码看起来没有做任何有用的事情,难以阅读,或者看起来很乏味,那么很可能 Python 有一些语言功能可以让您删除它。

The short answer to your question is no, you should use properties when needed. Ryan Tamyoko provides the long answer in his article Getters/Setters/Fuxors

The basic value to take away from all this is that you want to strive to make sure every single line of code has some value or meaning to the programmer. Programming languages are for humans, not machines. If you have code that looks like it doesn’t do anything useful, is hard to read, or seems tedious, then chances are good that Python has some language feature that will let you remove it.

飘过的浮云 2024-09-04 06:19:07

你的观察是正确的。这不是正常的 Python 编程风格。属性都是公共的,因此您只需访问(获取、设置、删除)它们,就像访问具有它们的任何对象(不仅仅是类或实例)的属性一样。很容易看出 Java 程序员何时学习 Python,因为他们的 Python 代码看起来就像使用 Python 语法的 Java!

我绝对同意之前所有的发帖者,特别是 @Maximiliano 的 Phillip 著名文章的链接 @Max 的建议,即任何比设置(和获取)类和实例属性的标准方法更复杂的方法都是使用 Properties (或描述符(进一步概括)来自定义属性的获取和设置! (这包括能够添加您自己的自定义版本的私有、受保护、朋友或任何您想要的策略,如果您想要公共以外的东西。)

作为一个有趣的演示,在 核心 Python 编程(第 13 章,第 13.16 节),我想出了一个使用描述符将属性存储到磁盘而不是内存中的示例!是的,这是一种奇怪的持久存储形式,但它确实向您展示了可能性的示例!

这是另一篇相关文章,您可能会发现它也很有用:
Python:多个属性,一个 setter/getter

Your observation is correct. This is not a normal style of Python programming. Attributes are all public, so you just access (get, set, delete) them as you would with attributes of any object that has them (not just classes or instances). It's easy to tell when Java programmers learn Python because their Python code looks like Java using Python syntax!

I definitely agree with all previous posters, especially @Maximiliano's link to Phillip's famous article and @Max's suggestion that anything more complex than the standard way of setting (and getting) class and instance attributes is to use Properties (or Descriptors to generalize even more) to customize the getting and setting of attributes! (This includes being able to add your own customized versions of private, protected, friend, or whatever policy you want if you desire something other than public.)

As an interesting demo, in Core Python Programming (chapter 13, section 13.16), I came up with an example of using descriptors to store attributes to disk instead of in memory!! Yes, it's an odd form of persistent storage, but it does show you an example of what is possible!

Here's another related post that you may find useful as well:
Python: multiple properties, one setter/getter

空城缀染半城烟沙 2024-09-04 06:19:07

我来这里就是为了这个答案(不幸的是我不能)。但我在其他地方找到了解决方法。下面的代码可以替代 get
类 get_var_lis:
def __init__(自身):
经过
def __call__(自我):
返回 [2,3,4]
def __iter__(自身):
返回迭代器([2,3,4])
some_other_var = get_var_lis

这只是一个解决方法。通过使用上述概念,您也可以轻松地在 py 中构建 get/set 方法。

I had come here for that answer(unfortunately i couldn't) . But i found a work around else where . This below code could be alternative for get .
class get_var_lis:
def __init__(self):
pass
def __call__(self):
return [2,3,4]
def __iter__(self):
return iter([2,3,4])
some_other_var = get_var_lis

This is just a workaround . By using the above concept u could easily build get/set methodology in py too.

筱果果 2024-09-04 06:19:07

我们的老师在课堂上展示了一个例子,解释我们何时应该使用访问器函数。

class Woman(Human):
    def getAge(self):
        if self.age > 30:
            return super().getAge() - 10
        else:
            return super().getAge()

Our teacher showed one example on class explaining when we should use accessor functions.

class Woman(Human):
    def getAge(self):
        if self.age > 30:
            return super().getAge() - 10
        else:
            return super().getAge()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文