Code sau minh họa sử dụng biến class (class attribute) - thường gọi nhầm là "global variable trong class scope".
Ví dụ
class Foo(object):
bar = 2 # Class attribute
foo = Foo()
print(Foo.bar) # 2
print(foo.bar) # 2
# Gán foo.bar tạo instance attribute, KHÔNG thay đổi class attribute
foo.bar = 3
print(Foo.bar) # 2 (class attribute không đổi)
print(foo.bar) # 3 (instance attribute mới)
# Để thay đổi class attribute, truy cập qua class
Foo.bar = 4
print(Foo.bar) # 4
print(foo.bar) # 3 (instance attribute vẫn 3, không bị ảnh hưởng)
Kết quả
2 2 2 3 4 3
Giải thích:
Foo.barlà class attribute (chia sẻ bởi tất cả instance).foo.bar = 3tạo instance attributebarchofoo, che khuất class attribute.- Đọc
foo.barưu tiên instance attribute, rồi mới đến class attribute. - Để sửa class attribute, dùng
ClassName.attr = value.