小心。這兩個msg屬性實際上存儲在兩個不同的字典中。 其中一個遮掩了另一個,但該屬性仍在字典中佔據空間。所以它沒有被使用,但仍然佔用一些內存。
class MyClass(object):
msg = 'FeeFiFoFum'
def __init__(self, msg):
self.msg = msg
m=MyClass('Hi Lucy')
請注意,我們有'Hi Lucy'
作爲值。該MyClass的的字典(通過m.__class__
訪問)
print(m.__dict__)
# {'msg': 'Hi Lucy'}
公告仍然有FeeFiFoFum
。
print(m.__class__.__dict__)
# {'__dict__': <attribute '__dict__' of 'MyClass' objects>, '__module__': '__main__', '__init__': <function __init__ at 0xb76ea1ec>, 'msg': 'FeeFiFoFum', 'some_dict': {}, '__weakref__': <attribute '__weakref__' of 'MyClass' objects>, '__doc__': 'my docstring', 'a_variable': None}
其它的(也許更簡單)的方式來看到這一點:直接
print(m.msg)
# Hi Lucy
print(MyClass.msg)
# FeeFiFoFum
儘管這些屬性存儲在不同的位置是正確的,但是當這些值是不可變的,並且您通過self而不是class對象訪問它們時,它們並沒有什麼不同。對於可變對象(some_dict)來說,它確實有很大的不同。 – 2010-02-22 01:28:05
對於不可變的「變量」(將msg和a_variable分配給None),我強烈建議您閱讀有關python的* names *:http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html #other-languages-have-variables 如果你認爲它是* tag * ** names **而不是* variables *,那麼它就沒有任何意義「初始化變量」。 「無」只是一個站在那裏的物體,除非你使用它,否則你不應該標記它。 – cregox 2010-04-14 17:39:20