python中类的定义方法_在Python中定义类变量的正确方法
這兩種方法都不一定正確或不正確,它們只是兩種不同的類元素:方法__init__之外的元素是靜態元素;它們屬于類。
__init__方法中的元素是對象(self)的元素;它們不屬于類。
使用一些代碼可以更清楚地看到:class MyClass:
static_elem = 123
def __init__(self):
self.object_elem = 456
c1 = MyClass()
c2 = MyClass()
# Initial values of both elements
>>> print c1.static_elem, c1.object_elem
123 456
>>> print c2.static_elem, c2.object_elem
123 456
# Nothing new so far ...
# Let's try changing the static element
MyClass.static_elem = 999
>>> print c1.static_elem, c1.object_elem
999 456
>>> print c2.static_elem, c2.object_elem
999 456
# Now, let's try changing the object element
c1.object_elem = 888
>>> print c1.static_elem, c1.object_elem
999 888
>>> print c2.static_elem, c2.object_elem
999 456
如您所見,當我們更改類元素時,兩個對象的類元素都發生了更改。但是,當我們更改object元素時,另一個對象保持不變。
超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生總結
以上是生活随笔為你收集整理的python中类的定义方法_在Python中定义类变量的正确方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用python处理excel 数据分析_
- 下一篇: python如何读入dat数据_pyth