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

2024-03-27

我有课Foo带有类变量remote。我可以访问类变量吗remote using self.remote?

class Foo:
   remote = False

   def __init__(self):
       self.remote = True 

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

分配remote to self in __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 is essentially equivalent to self.__class__.remote but, in general, you should avoid grabbing dunder names (__*__) when there's a built in that does it for you (type in this case)

它们存在于不同的字典中并且是不同的变量。self.remote生活在实例字典中,同时class.remote在课堂词典中。

>>> Foo().__dict__['remote']
True
>>> Foo.__dict__['remote']
False

当您通过访问cls with a classmethod (or type(self)在正常方法中)当您访问时,您将获得第一类self你得到实例一。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我可以使用 self 访问类变量吗? 的相关文章

随机推荐