# Python对象的类变量和实例变量

2018年4月22日 / 33次阅读
Python

Class variables are shared in the sense that they are accessed by all objects (instances) of that class. There is only copy of the class variable and when any one object makes a change to a class variable, the change is reflected in all the other instances as well.

class Employee:

empCount = 0

def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1

>>>
>>> e1 = test.Employee('e1','200')
>>> e1.empCount
1
>>> e2 = test.Employee('e2','200')
>>> e1.empCount
2
>>> e2.empCount
2
>>> e3 = test.Employee('e3','200')
>>> e2.empCount
3
>>> e3.empCount
3
>>>

>>>
>>> e1.empCount = 10
>>> e1.empCount
10
>>> e2.empCount
3
>>> e3.empCount
3
>>>

class Dog:

tricks = []             # mistaken use of a class variable

def __init__(self, name):
self.name = name

self.tricks.append(trick)

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.tricks                # unexpectedly shared by all dogs
['roll over', 'play dead']

Object variables are owned by each individual object/instance of the class. In this case, each object has its own copy of the field i.e. they are not shared and are not related in any way to the field by the samen name in a different instance of the same class. An example will make this easy to understand.

>>> e1.gender = 'male'
>>> e2.gender = 'female'
>>> e1.gender
'male'
>>> e2.gender
'female'
>>> e3.gender
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'Employee' object has no attribute 'gender'
>>>

ricequant网站的代码，就是通过对象的实例变量，在各个函数之间传递信息。

Python的dict字典类型也有这个直接“挂接”的特性，直接对一个不存在的key进行赋值操作：

>>>
>>> d = {}
>>> d['a']='111'
>>> d
{'a': '111'}
>>>

Ctrl+D 收藏本页