分別給Python類和實例增長屬性和方法

#定義一個類Student
class Student(object):
    pass

#給類增長一個屬性name
Student.name = 'xm'
print Student.name  # xm

#給類增長一個方法set_age
def set_age(self,age):
    self.age = age
Student.set_age = set_age
s = Student()
s.set_age(20)
print s.age  #20

#給實例屬性增長一個屬性:
s1 = Student()
s1.name = 'xh'
print s1.name  #xh

#給實例屬性增長一個方法:
def set_score(self,score):
    self.score = score

from types import MethodType
s1.set_score = MethodType(set_score,s1)
s1.set_score(88)
print s1.score  #88

#而其它的實例對象並無set_score方法 print s.score #'Student' object has no attribute 'score'
相關文章
相關標籤/搜索