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


类变量与实例变量

Python 中 __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-Jun-2020

已浏览 1 千次

开启您的 事业

完成课程获得认证

开始
广告
© . All rights reserved.