>>> obj=MyObject() >>> hasattr(obj,'x') True >>> hasattr(obj,'y') False >>> setattr(obj,'y',18) >>> hasattr(obj,'y') True >>> getattr(obj,'y') 18 >>> getattr(obj,'z',404) 404 >>> getattr(obj,'z') Traceback (most recent call last): File "<pyshell>", line 1, in <module> AttributeError: 'MyObject' object has no attribute 'z' >>> getattr(obj,'z','this is a error') 'this is a error'
>>> class Student(object): pass
>>> s=student() Traceback (most recent call last): File "<pyshell>", line 1, in <module> NameError: name 'student' is not defined >>> s=Student() >>> s.name = 'Mickh' >>> print(s.name) Mickh >>> print(Student.name) Traceback (most recent call last): File "<pyshell>", line 1, in <module> AttributeError: type object 'Student' has no attribute 'name' >>> def set_age(self,age): self.age=age
>>> from types import MethodType >>> s.set_age=MethodType(set_age,s) >>> s.set_age(25) >>> s.age 25 >>> class Student(object): __slots__=('name','age')
>>> s=Student() >>> s.name ='xd' >>> s.age =34 >>> s.score=65 Traceback (most recent call last): File "<pyshell>", line 1, in <module> AttributeError: 'Student' object has no attribute 'score' >>>
class Student(object): def get_score(self): return self._score def set_score(self,value): if not isinstance(value,int): raise ValueError('score must be an integer!') if value <0 or value >100: raise ValueError('score must between 0~100') self._score=value