分别给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'

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM