当我们在类内但在任何方法外声明变量时,在python中将其称为类或静态变量。可以通过类来引用类或静态变量,但不能直接通过实例来引用。
类或静态变量与具有相同名称的任何其他成员变量完全不同,并且不与之冲突。下面是一个程序来演示类或静态变量的使用-
class Fruits(object): count = 0 def __init__(self, name, count): self.name = name self.count = count Fruits.count = Fruits.count + count def main(): apples = Fruits("apples", 3); pears = Fruits("pears", 4); print (apples.count) print (pears.count) print (Fruits.count) print (apples.__class__.count) # This is Fruit.count print (type(pears).count) # So is this if __name__ == '__main__': main()
3 4 7 7 7
另一个示例演示在类级别定义的变量的使用-
class example: staticVariable = 9 # Access through class print (example.staticVariable) # Gives 9 #Access through an instance instance = example()print(instance.staticVariable) #Again gives 9 #Change within an instance instance.staticVariable = 12 print(instance.staticVariable) # Gives 12 print(example.staticVariable) #Gives 9
9 9 12 9