数据属性初始化

发布于 2024-10-24 06:39:40 字数 626 浏览 0 评论 0原文

我有一个这样的类

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 技术交流群。

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

发布评论

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

评论(1

野鹿林 2024-10-31 06:39:40

不,只有在调用 doSomething() 后才会创建 self.counter。在Python中,实例属性是动态的,可以在运行时创建。要在创建对象时使用 self.counter,请将其初始化放入构造函数中:

class SomeClass:
    def __init__(self):
        self.counter = None
    def doSomething(self):
        self.counter = 50

现在 SomeClass 的所有实例都将具有 self.counter 从一开始就可用,尽管在调用 doSomething 之前其值将为 None。当然,这个主题有很多变体,可以让您实现您感兴趣的确切语义。

No, self.counter is created only then doSomething() is called. In Python, instance attributes are dynamic and can be created at runtime. To have self.counter available from the creation of the object, put its initialization in a constructor:

class SomeClass:
    def __init__(self):
        self.counter = None
    def doSomething(self):
        self.counter = 50

Now all instances of SomeClass will have self.counter available from start, although its value will be None until doSomething is called. Natually, there are many variations on this theme to allow you to implement the exact semantics you're interested in.

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