数据属性初始化
我有一个这样的类
class SomeClass:
def doSomething(self):
self.counter = 50
,我为 SomeClass
创建一个实例 x
x = SomeClass()
当我尝试获取如下计数器的值时: x.counter
I收到以下错误 -
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: SomeClass instance has no attribute 'counter'
但是在我调用成员函数 x.doSomething() 并查找 data 属性后,它是可用的。
>>> x.doSomething()
>>> x.counter
50
为什么会这样呢?实例创建之后所有的数据属性不是都可用了吗?
谢谢。
I have a class like this
class SomeClass:
def doSomething(self):
self.counter = 50
I create an instance x
for SomeClass
x = SomeClass()
When I try to get the value of counter like this: x.counter
I get the following error -
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: SomeClass instance has no attribute 'counter'
But After I call the member function x.doSomething()
and then look for the data attribute, it is available.
>>> x.doSomething()
>>> x.counter
50
Why is it like this? Won't all the data attributes be available as soon as the instance is created?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,只有在调用
doSomething()
后才会创建self.counter
。在Python中,实例属性是动态的,可以在运行时创建。要在创建对象时使用self.counter
,请将其初始化放入构造函数中:现在
SomeClass
的所有实例都将具有self.counter
从一开始就可用,尽管在调用doSomething
之前其值将为None
。当然,这个主题有很多变体,可以让您实现您感兴趣的确切语义。No,
self.counter
is created only thendoSomething()
is called. In Python, instance attributes are dynamic and can be created at runtime. To haveself.counter
available from the creation of the object, put its initialization in a constructor:Now all instances of
SomeClass
will haveself.counter
available from start, although its value will beNone
untildoSomething
is called. Natually, there are many variations on this theme to allow you to implement the exact semantics you're interested in.