构造函数(Python)之外的方法中的实例变量——为什么以及如何? [英] Instance variables in methods outside the constructor (Python) -- why and how?

查看:20
本文介绍了构造函数(Python)之外的方法中的实例变量——为什么以及如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题涉及在类构造函数之外的方法中初始化的实例变量.这是针对 Python 的.

My questions concern instance variables that are initialized in methods outside the class constructor. This is for Python.

我先说说我的理解:

  1. 类可以定义构造函数,也可以定义其他方法.
  2. 实例变量通常在构造函数中定义/初始化.
  3. 但是实例变量也可以在构造函数之外定义/初始化,例如在同一类的其他方法中.
  4. (2) 和 (3) 的例子——参见 Cat 中的 self.meowself.roar下面的类:

  1. Classes may define a constructor, and it may also define other methods.
  2. Instance variables are generally defined/initialized within the constructor.
  3. But instance variables can also be defined/initialized outside the constructor, e.g. in the other methods of the same class.
  4. An example of (2) and (3) -- see self.meow and self.roar in the Cat class below:

class Cat():

    def __init__(self):
        self.meow = "Meow!"
    def meow_bigger(self):
        self.roar = "Roar!"

我的问题:

  1. 为什么在构造函数中初始化实例变量是最佳实践?

  1. Why is it best practice to initialize the instance variable within the constructor?

如果在构造函数以外的方法中定期初始化实例变量,会出现什么一般/特定的混乱?(例如,在他的 Python 编程中阅读了 Mark Lutz 的 Tkinter 指南,我认为它很棒,我注意到用于保存 PhotoImage 对象/引用的实例变量是在进一步的方法中初始化的,而不是在构造函数中.它似乎没有问题,但从长远来看,这种做法会导致问题吗?)

What general/specific mess could arise if instance variables are regularly initialized in methods other than the constructor? (E.g. Having read Mark Lutz's Tkinter guide in his Programming Python, which I thought was excellent, I noticed that the instance variable used to hold the PhotoImage objects/references were initialized in the further methods, not in the constructor. It seemed to work without issue there, but could that practice cause issues in the long run?)

在什么情况下,在其他方法中而不是在构造函数中初始化实例变量更好?

In what scenarios would it be better to initialize instance variables in the other methods, rather than in the constructor?

<小时>

  1. 据我所知,实例变量不是在类对象创建时存在,而是在类对象实例化之后存在.继续我上面的代码,我证明了这一点:

  1. To my knowledge, instance variables exist not when the class object is created, but after the class object is instantiated. Proceeding upon my code above, I demonstrate this:

>> c = Cat() 
>> c.meow
'Meow!'
>> c.roar
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
AttributeError: 'Cat' object has no attribute 'roar'
>>> c.meow_bigger()
>>> c.roar
'Roar!'

原来如此:

  • 一开始我无法访问实例变量 (c.roar).
  • 然而,在我调用实例方法c.meow_bigger()一次后,我突然可以访问实例变量c.roar.
  • 为什么会出现上述行为?
  • I cannot access the instance variable (c.roar) at first.
  • However, after I have called the instance method c.meow_bigger() once, I am suddenly able to access the instance variable c.roar.
  • Why is the above behaviour so?

感谢您帮助我理解.

推荐答案

为什么最好的做法是在内部初始化实例变量构造函数?

Why is it best practice to initialize the instance variable within the constructor?

清晰度.

因为这样可以很容易地一目了然地查看类的所有属性.如果在多个方法中初始化变量,不阅读每一行代码就很难理解完整的数据结构.

Clarity.

Because it makes it easy to see at a glance all of the attributes of the class. If you initialize the variables in multiple methods, it becomes difficult to understand the complete data structure without reading every line of code.

__init__ 中初始化也使文档更容易.对于您的示例,您不能写Cat 的实例具有 roar 属性".相反,您必须添加一段解释 Cat 的实例可能具有roar"属性的段落,但仅在调用meow_louder"方法之后.

Initializing within the __init__ also makes documentation easier. With your example, you can't write "an instance of Cat has a roar attribute". Instead, you have to add a paragraph explaining that an instance of Cat might have a "roar" attribute, but only after calling the "meow_louder" method.

清晰为王.我见过的最聪明的程序员之一曾经告诉我向我展示你的数据结构,我可以在不看任何代码的情况下告诉你你的代码是如何工作的".虽然这有点夸张,但绝对有道理.学习代码库的最大障碍之一是理解它操作的数据.

Clarity is king. One of the smartest programmers I ever met once told me "show me your data structures, and I can tell you how your code works without seeing any of your code". While that's a tiny bit hyperbolic, there's definitely a ring of truth to it. One of the biggest hurdles to learning a code base is understanding the data that it manipulates.

如果实例变量是在构造函数以外的方法中定期初始化?

What general/specific mess could arise if instance variables are regularly initialized in methods other than the constructor?

最明显的一点是,一个对象可能没有在程序的所有部分都可用的属性,导致不得不添加大量额外的代码来处理属性未定义的情况.

The most obvious one is that an object may not have an attribute available during all parts of the program, leading to having to add a lot of extra code to handle the case where the attribute is undefined.

在什么场景下初始化实例变量比较好在其他方法中,而不是在构造函数中?

In what scenarios would it be better to initialize instance variables in the other methods, rather than in the constructor?

我认为没有.

注意:您不一定必须使用它的最终值来初始化属性.在您的情况下,将 roar 初始化为 None 是可以接受的.它已被初始化为 something 这一事实表明它是该类维护的一段数据.如果以后值改变就好了.

Note: you don't necessarily have to initialize an attribute with it's final value. In your case it's acceptable to initialize roar to None. The mere fact that it has been initialized to something shows that it's a piece of data that the class maintains. It's fine if the value changes later.

这篇关于构造函数(Python)之外的方法中的实例变量——为什么以及如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆