解释 Python 中 class __init__() 函数内和外变量。


类变量与实例变量

Python 中 class __init__ 函数外部的所有变量都是类变量,而相同函数内部的那些是实例变量。通过检查下面的代码,可以更好地理解类变量和实例变量之间的区别

示例

class MyClass:
    stat_elem = 456
    def __init__(self):
        self.object_elem = 789
c1 = MyClass()
c2 = MyClass()
# Initial values of both elements
>>> print c1.stat_elem, c1.object_elem
456 789
>>> print c2.stat_elem, c2.object_elem
456 789
# Let's try changing the static element
MyClass.static_elem = 888
>>> print c1.stat_elem, c1.object_elem
888 789
>>> print c2.stat_elem, c2.object_elem
888 789
# Now, let's try changing the object element
c1.object_elem = 777
>>> print c1.stat_elem, c1.object_elem
888 777
>>> print c2.stat_elem, c2.object_elem
888 789

更新于: 13-六月-2020

1 千 + 浏览量

开启您的职业

通过完成课程获得认证

开始
广告