如何设置和访问类的属性?

14 浏览
0 Comments

如何设置和访问类的属性?

此问题已经有答案:

如何在方法中访问“静态”类变量?

假设我有这段代码:

class Example(object):
    def the_example(self):
        itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)

当我尝试运行它时,我收到一个错误提示:

Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'Example' object has no attribute 'itsProblem'

我该如何访问这个属性?我尝试增加另一个方法来返回它:

    def return_itsProblem(self):
        return itsProblem

但问题仍然存在。

admin 更改状态以发布 2023年5月23日
0
0 Comments

你正在声明一个局部变量,而不是一个类变量。要设置实例变量(属性),请使用

class Example(object):
    def the_example(self):
        self.itsProblem = "problem"  # <-- remember the 'self.'
theExample = Example()
theExample.the_example()
print(theExample.itsProblem)

要设置类变量(也称为静态成员),请使用

class Example(object):
    def the_example(self):
        Example.itsProblem = "problem"
        # or, type(self).itsProblem = "problem"
        # depending what you want to do when the class is derived.

0
0 Comments

简单回答

在你的例子中,itsProblem是一个局部变量。你必须使用self来设置和获取实例变量。你可以在__init__方法中设置它。这样你的代码就是:

class Example(object):
    def __init__(self):
        self.itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)

但是,如果你想要一个真正的类变量,那么直接使用类名就可以了:

class Example(object):
    itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)
print (Example.itsProblem)

但要注意这一点,因为theExample.itsProblem会自动设置为等于Example.itsProblem,但它并不是同一个变量,可以独立地进行更改。

一些解释

在Python中,变量可以动态创建。因此,你可以做以下操作:

class Example(object):
    pass
Example.itsProblem = "problem"
e = Example()
e.itsSecondProblem = "problem"
print Example.itsProblem == e.itsSecondProblem 

打印结果为

True

这正是你在之前的例子中所做的。

的确,在Python中,我们把self作为this来使用,但它不仅仅是这样。self是任何对象方法的第一个参数,因为第一个参数总是对象引用。这是自动的,无论你是否将其称为self

这意味着你可以这样做:

class Example(object):
    def __init__(self):
        self.itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)

或者:

class Example(object):
    def __init__(my_super_self):
        my_super_self.itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)

完全一样。任何对象方法的第一个参数都是当前对象,我们只是把它称为self作为一种约定。你只需要向该对象添加一个变量,就像你在外面添加一样。

现在,关于类变量。

当你这样做时:

class Example(object):
    itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)

你会注意到我们首先设置了一个类变量,然后我们访问一个对象(实例)变量。我们从来没有设置这个对象变量,但它正常工作,这是怎么可能的呢?

Python首先尝试获取对象变量,但是如果找不到它,它将提供类变量。 警告:类变量在实例之间共享,而对象变量不共享。

总之,永远不要使用类变量来设置对象变量的默认值。使用__init__来实现。

最终,您将了解Python类本身就是实例,因此也是对象,这为理解上述内容提供了新的视角。 一旦您意识到这一点,请回来重新阅读此内容。

0