如果直接在Animal类本身绑定一个属性,可在class中定义,这种属性时类属性:
>>> class Animal(object): ... name = "name" ... >>> a = Animal() >>> a.name # 实例a没有name属性,会查找class的name属性 'name' >>> Animal.name # 打印类的name属性 'name' >>> a.name='name_object' # 给实例a绑定name属性 >>> a.name # 实例属性优先级比类属性高,所有屏蔽了类的name属性 'name_object'
实例属性归各个实例所有,互不干扰。类属性属于类所有,所有实例共享一个类属性。不要对实例属性和类属性使用相同的名字,否则将发生难以发现的错误
在程序运行时可以动态给class绑定属性,但如果想限制实例的属性,例如只允许给Student类添加name或age属性,可以在提供定义class时,设置一个特殊的__slots__变量:
>>> class Student(object):
... __slots__=('name','age') # 通过tuple设置允许绑定的属性明恒
...
>>> a = Student()
>>> a.name="name" # 绑定属性name
>>> a.other=123 # 绑定属性other,不在__slots__定义中,出现错误
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'other'
other不在__slots__定义中,所以不能绑定other属性,得到AttributeError错误。__slots__定义的属性仅对当前实例起作用,对继承的子类不起作用。
在java中,如果定义了一个属性,一般会实现这个属性的getter和setter方法。在python中,可以通过@property装饰器将方法变成属性调用,这样既能检查参数,又能用属性这样简单的方式来访问变量。
>>> class Student(object):
... @property
... def score(self):
... return self._score
...
... @score.setter
... def score(self, value):
... if not isinstance(value,int):
... raise ValueError('score must be integer')
... if value > 100 or value < 0:
... raise ValueError('score must between 0-100')
... self._score=value
>>> s = Student()
>>> s.score=-1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 10, in score
ValueError: score must between 0-100
>>> s.score=10 # 实际转化为s.set_score(10)
>>> s.score # 实际转化为s.get_score()
10
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-70754-12.html
收二手家电者的广告词