Python 中的类变量和实例变量(关键词:Python/类变量/实例变量)

版权声明:本文为博主原创文章,可以转载,但转载前请联系博主。 https://blog.csdn.net/qq_33528613/article/details/84243443

类变量: class 语句的顶层进行赋值的变量,会被附加在类中,被所有实例所共享;
实例变量:附加在实例上的变量,不被共享,可通过这 2 种方式创建或修改:

  1. aInstance.name = sth 的形式;
  2. 类的实例方法中,self.name = sth 的形式。
>>> class C:
	a = 0
	def __init__(self, name):
		self.name = name

		
>>> c1 = C('heli')
>>> c2 = C('henry')
>>> c1.name, c2.name
('heli', 'henry')
>>> C.a, c1.a, c2.a
(0, 0, 0)
>>> C.a = 2
>>> C.a, c1.a, c2.a
(2, 2, 2)
>>> c1.a = 5
>>> C.a, c1.a, c2.a
(2, 5, 2)
>>> c1.tech = 'sss'
>>> c2.tech

Traceback (most recent call last):
  File "<pyshell#204>", line 1, in <module>
    c2.tech
AttributeError: C instance has no attribute 'tech'

c1.tech = 'sss'的解释:对实例属性进行赋值运算,会在该实例内创建或修改变量名,而不是在共享的类中。对 c1.tech 进行赋值,会把该变量名附加在 c1 本身上。

类属性可以管理贯穿所有实例的信息。例如,所产生的实例的数目的计数器。

>>> class C:
	instanceCount = 0
	def __init__(self):
		C.instanceCount += 1

>>> c1 = C()
>>> C.instanceCount, c1.instanceCount
(1, 1)
>>> c2 = C()
>>> C.instanceCount, c1.instanceCount, c2.instanceCount
(2, 2, 2)

参考文献:

  1. 《Python学习手册(第 4 版)》 - 第28章 - class 语句 - P686——P689;
  2. https://github.com/taizilongxu/interview_python#4-类变量和实例变量
  3. http://stackoverflow.com/questions/6470428/catch-multiple-exceptions-in-one-line-except-block。

猜你喜欢

转载自blog.csdn.net/qq_33528613/article/details/84243443