python中类变量和实例变量

it2026-08-23  3

1. 类变量和实例变量

在Python Tutorial中对于类变量和实例变量是这样描述的:

Generally speaking, instance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the class:

通常来说,实例变量是对于每个实例都独有的数据,而类变量是该类所有实例共享的属性和方法。

其实我更愿意用类属性和实例属性来称呼它们,但是变量这个词已经成为程序语言的习惯称谓。一个正常的示例是:

class Dog: kind = 'canine' # class variable shared by all instances def __init__(self, name): self.name = name # instance variable unique to each instance 类Dog中,类属性kind为所有实例所共享;实例属性name为每个Dog的实例独有。

转载于:https://www.cnblogs.com/CK85/p/10291827.html

最新回复(0)