在Python中设计类时,建议将成员变量放在哪里?
我正在尝试熟悉 python 中的类。在 C++ 中,关于成员变量,类的结构对我来说似乎很简单。您只需在类作用域的开头或末尾声明它们(根据需要作为公共或私有)并根据需要使用它们。
python 中如何处理这个问题?
现在我倾向于编写类并在需要时声明变量:
class Foo():
standard = "standard"
def __init__(self, arg_1, arg_2):
self.first = arg_1
self.second = self.do_something(arg_2)
def do_something(param):
second = # do something with self.standard and param and store it.
return second
def do_another_thing():
self.third = # do another thing.
我知道,类也可以在没有成员变量的情况下定义,并且可以动态添加它们。
class Foo():
pass
foo = Foo()
foo.a = "a"
# etc.
把所有这些放在一起让我很困惑,因为代码变得更难阅读。
所以我的问题是,关于 python 中的成员变量,设计类的推荐方法是什么?
编辑:
我问的方式具有误导性。对此感到抱歉!不过,这些答案帮助我理解了其他事情。 ;-)
我会改写:我不是在问如何解决我对在类中定义的变量和在编码时动态添加的变量的困惑。
我想要解决的是我对 python 类的设计以及成员变量的困惑。我的意思是,将它们放在最好的位置,让潜在的代码读者无需搜索即可看到所有内容。这就是我提到 C++ 中的类的原因。所有成员变量都有一个位置,如果您想知道类中存储了哪些数据,您可以查看类的开头或结尾,然后获得所需的所有信息。
在我上面写的示例中,您会看到,standard
位于 __init__(self, ...)
、first
和 second< 之上/code> 位于
__init(self,...)
内部,third
位于 do_something()
内部,如果类很大,则可以低于所有其他方法。因此,您必须逐行搜索它,否则永远不会意识到它的存在。
我希望我的问题现在能得到更好的提出。 :-)
I am trying to get familiar with classes in python. In C++ the structure of a class seems straightforward to me, regarding the member variables. You just declare them at the beginning of the class scope or at the end (as public or private, as desired) and work with them as you need.
How is this handled in python?
Right now I tend to write the class and declare the variable where needed:
class Foo():
standard = "standard"
def __init__(self, arg_1, arg_2):
self.first = arg_1
self.second = self.do_something(arg_2)
def do_something(param):
second = # do something with self.standard and param and store it.
return second
def do_another_thing():
self.third = # do another thing.
I know, that a class can be defined too without member variables and they can be added dynamically.
class Foo():
pass
foo = Foo()
foo.a = "a"
# etc.
Throwing all of this together it confuses me, since the code becomes harder to read.
So my question is, what is the recommended way to design a class, regarding member variables in python?
Edit:
The way I asked was misleading. Sorry about that! The answers helped me to understand other things, though. ;-)
I'll rephrase: I am not asking for how to solve my confusion regarding variables defined inside the class and variables added dynamically while coding.
What I wanted to solve was my confusion about the design of a python class, regarding member variables. I mean, where to put them the best, to allow a potential reader of the code to see everything without having to search for them. That's why I mentioned classes in C++. You have one place for all member variables and if you want to know which data is stored in the class you look at the beginning or the end of a class, and you get all the information you need.
In the example I wrote above, you see, standard
is above __init__(self, ...)
, first
and second
are inside of __init(self,...)
and third
is inside do_something()
, which if the class is big could be below all other methods. So you would have to search for it line by line, or never realise it existed.
I hope my question is better proposed now. :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
所有这些方法都有效,因此这取决于您自己的代码标准和文档。
就我个人而言,我认为在 __init__ 函数中初始化“公共”成员属性是一种很好的做法。这使得它们是什么变得显而易见,并且应该通过在类文档字符串中记录它们来强调这一点。
您仍然可以在整个代码中动态添加变量,但我更喜欢仅在预计不会在类本身之外访问变量的情况下使用此方法(我通常使用单个初始下划线 -
self._foo
来指出这一点)。完全在类外部分配属性也有一个用例,但对我来说,这严格是为了使用该类实例的代码的方便,而不是类代码本身。例如,在 Django 中,我经常在
request
对象中设置自定义属性,因为我知道该属性将被传递,因此我可以在代码中的其他位置访问这些属性。然而,并不期望对象本身意识到这个额外的包袱。All of these approaches work, so it's a matter of your own code standards and documentation.
Personally, I regard it as good practice to initialise the "public" member attributes in the
__init__
function. That makes it obvious what they are, and this should be emphasised by documenting them in the class docstring.You still can add variables dynamically throughout the code, but I prefer to only use this where the variables are not expected to be accessed outside the class itself (I usually use a single initial underscore -
self._foo
to indicate this).Assigning properties outside the class completely also has a use case, but for me this is strictly for the convenience of the code that's using that class instance, rather than the class code itself. For example, in Django I quite frequently set custom attributes in the
request
object, since I know that will be passed around and I can therefore access those attributes elsewhere in the code. However, there is no expectation that the object itself is aware of that extra baggage.当你写信的时候你自己已经回答了你的问题
我使用更容易阅读的内容。因此,我编写了与您的第一个代码片段类似的代码。
当您尝试权衡两种可能的方法时,请启动 python 解释器并执行:
import this
You have answered your question yourself when you wrote
I use what is easier to read. So, I write code similar to your first code snippet.
When you are trying to weigh two possible approaches against each other, fire up your python interpreter and execute:
import this
正如您所说,您可以随时在任何方法中创建成员变量。但是,我倾向于在 __init__ 中创建所有成员变量,如果无法在 __init__ 中为它们分配实际值,则将它们初始化为合理的默认值。这对我来说有两件事:1.如果在将来的某个时候我不想知道“这个变量到底是从哪里来的”,我可以更好地理解我的类。 2. 它可以防止“在分配之前使用”错误。
As you've stated, you can create a member variable in any method at any time. However, I favor creating all of my member variable in
__init__
, initializing them to a reasonable default value if I can't assign the actual value to them in__init__
. This does two things for me: 1. I can understand my classes better if at some future point I'm not wondering 'where the heck did that variable come from'. 2. It protects against 'used before assigned' errors.