分别给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‘ 相关推荐
bcbeer 2020-05-02
class Singleton: def __new__: # 关键在于这,每一次实例化的时候,我们都只会返回这同一个instance对象 if not hasattr: cls.instance =
lhxxhl 2020-05-16
PHP学习笔记 2020-05-07
DCXabc 2020-05-01
fly00love 2020-03-08
liusarazhang 2020-03-06
zhuxianfeng 2020-03-03
Kwong 2020-03-01
ladysosoli 2020-03-01
liugan 2020-02-25
Dimples 2020-02-14
wangqing 2020-02-13
fanhuasijin 2020-02-03
文山羊 2020-02-01