Python 中的类变量还是静态变量?
当我们在类外部但方法内部声明变量时,在 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
广告