如何在Python方法中访问类变量

huangapple go评论72阅读模式
英文:

How to access a class variable in a method in python

问题

标题已经说了一切。我想要使用一个类变量,但我一直收到一个名称错误。我该怎么解决这个问题?

这是我的代码:

class a:
    var = 0

    def foo():
        print(a.var)
    foo()

b = a()

这是错误代码:

NameError: name 'a' is not defined
英文:

Title says it all. I want to use a class variable but I keep getting a name error. What can I do to solve this?

Here's my code:

class a:
    var = 0

    def foo():
        print(a.var)
    foo()

b = a()

Here's the error code:

NameError: name 'a' is not defined

答案1

得分: 1

这是您想要实现的吗?

class a:
    var = 0

    def foo(self):
        print(self.var)

b = a()

b.foo()  # "print(b.var)" also works

上面的代码产生了以下结果:

0
英文:

Is this what you want to achieve?

class a:
    var = 0

    def foo(self):
        print(self.var)

b = a()

b.foo()  # "print(b.var)" also works

Above code gives the following result:

0

答案2

得分: 0

foo函数内,打印语句应通过调用self.var来访问变量var,而不是a.var。此外,方法foo应该具有默认参数self,如下所示:

def foo(self):
    ...
英文:

Inside the foo function, the print statement should access the variable var by calling self.var, and not a.var. Also, the method foo should have a default parameter of self, like so:

def foo(self):
    ...

答案3

得分: 0

Python 对于类变量的处理方式有点棘手,我认为。
以这段代码为例:

class a:
    var = 0

    def foo(self):
        self.my_name = [k for k,v in globals().items() if v is self][0]
        print(f'----------{self.my_name}.var address:', id(a.var))
        print(f'self.var in {self.my_name} instance:', id(self.var))

    def change(self):
        print(f'changing self.var value to 1 in {self.my_name} instance')
        self.var = 1

b = a()
c = a()
b.foo()
c.foo()

c.change()

b.foo() 
c.foo()

输出结果如下:

----------b.var address: 140434476089552
self.var in b instance: 140434476089552
----------c.var address: 140434476089552
self.var in c instance: 140434476089552
changing self.var value to 1 in c instance
----------b.var address: 140434476089552
self.var in b instance: 140434476089552
----------c.var address: 140434476089552
self.var in c instance: 140434476089584

您可以看到,在c上的某些写操作(self.var = 1)创建了一个新的变量(实例变量)供c使用。这是您需要注意的问题,否则您将不会使用类变量,而只会使用不相关的实例变量。
相反,您应该始终使用 a.var。这也是为什么访问类变量的方法不应该有 self 作为参数,以避免混淆的原因。

英文:

Python acts in a bit of a tricky way with class variables imo.
Taking this snippet of code as example :

class a:
    var = 0

    def foo(self):
        self.my_name = [k for k,v in globals().items() if v is self][0]
        print(f'----------{self.my_name}.var adress:', id(a.var))
        print(f'self.var in {self.my_name} instance:', id(self.var))

    def change(self):
        print(f'changing self.var value to 1 in {self.my_name} instance')
        self.var = 1

b = a()
c = a()
b.foo()
c.foo()

c.change()

b.foo() 
c.foo()

which outputs

----------b.var adress: 140434476089552
self.var in b instance: 140434476089552
----------c.var adress: 140434476089552
self.var in c instance: 140434476089552
changing self.var value to 1 in c instance
----------b.var adress: 140434476089552
self.var in b instance: 140434476089552
----------c.var adress: 140434476089552
self.var in c instance: 140434476089584

You can see that some write operation (self.var = 1) in the c context did create a new variable (an instance variable) for c. This is something you really have to be aware of, otherwise you won't work with class variables but only uncorrelated instance variables.
Instead, you should always use a.var. This is also why method accessing class variables only should not have self as a parameter, to avoid this confusion.

huangapple
  • 本文由 发表于 2023年7月10日 21:16:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76654140.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定