我可以使用self访问类变量吗?

时间:2017-06-09 14:46:24

标签: python python-3.x class

我有一个类Foo,其类变量为remote。我可以使用remote访问类变量self.remote吗?

class Foo:
   remote = False

   def __init__(self):
       self.remote = True 

   @classmethod
   def print_remote(cls):
       print(cls.remote) #prints False but why? 

3 个答案:

答案 0 :(得分:8)

remote中将self分配给__init__表示当您通过instance.remote访问self时,首先找到self(授予不存在描述符)。要获得这两个选项,请从type(self)def print_remote(self): print(type(self).remote) # class remote print(self.remote) # instance remote 访问,即从实例或类访问:

type(self).remote

self.__class__.remote基本上等同于__*__但是,一般情况下,你应该避免使用内置的dunder名称(type)你(在这种情况下是self.remote

这些字典存在于不同的字典中,并且是不同的变量。 class.remote生活在实例dict中,同时在类dict中>>> Foo().__dict__['remote'] True >>> Foo.__dict__['remote'] False

cls

当您使用classmethod(或普通方法为type(self))通过self访问时,当您通过{{1}}访问时,您将获得第一个课程你得到一个实例。

答案 1 :(得分:3)

In [1]: class Foo:
   ...:     x = 0
   ...:

In [2]: f = Foo()

In [4]: f.__dict__ # empty
Out[4]: {}

In [5]: Foo.__dict__ # have the variable x = 0
Out[5]:
mappingproxy({'__dict__': <attribute '__dict__' of 'Foo' objects>,
              '__doc__': None,
              '__module__': '__main__',
              '__weakref__': <attribute '__weakref__' of 'Foo' objects>,
              'x': 0})

当你尝试访问一个对象中的一个变量时,Python会首先查看该对象,如果它不在那里,那么它会在类dict中查找。

In [6]: Foo.x = 10 # changing class variable

In [7]: f.__dict__ # still empty.
Out[7]: {}

In [8]: f.x # gives you Foo's x as object doesn't have that item.
Out[8]: 10

In [9]: f.x = 20 # this line creates a new variable in x. Now both class and object has their own variable x

In [10]: f.__dict__ # f has its own x.
Out[10]: {'x': 20}

In [11]: Foo.__dict__ # Foo has its own x.
Out[11]:
mappingproxy({'__dict__': <attribute '__dict__' of 'Foo' objects>,
              ...
              'x': 10})
In [12]: f.x # always you will get the value from f.__dict__
Out[12]: 20
In [16]: f.x = 50 # changing the value of object's variable

In [17]: Foo.x # above statement didn't affect class's variable.
Out[17]: 10

In [13]: del f.x # delete object's x

In [14]: f.x # now f doesn't have x, you get the value from class Foo.
Out[14]: 10

答案 2 :(得分:1)

是的,您可以使用self访问类变量。但是,如果你有一个实例变量,当你使用self时,你将访问实例变量,因为它会影响类变量。

相关问题