运行过程中给类添加方法 types.MethodType

class Person(object):

    def __init__(self,name = None,age = None):
        self.name = name#类中拥有的属性
        self.age = age

    def eat (self):
        print("%s在吃东西"%(self.name))

p = Person("XiaoLiu",22)
p.eat()#调用Person中的方法

def run(self,speed):#run方法为需要添加到Person类中的方法
    # run方法 self 给类添加方法,使用self指向该类
    print("%s在以%d米每秒的速度在跑步"%(self.name,speed))

run(p,2)#p为类对象

import types
p1= types.MethodType(run,p)#p1只是用来接收的对象,MethodType内参数为 函数+类实例对象 ,接收之后使用函数都是对类实例对象进行使用的
# 第二个参数不能够使用类名进行调用
p1(2) #p1(2)调用实际上时run(p,2)


'''
XiaoLiu在吃东西
XiaoLiu在以2米每秒的速度在跑步
XiaoLiu在以2米每秒的速度在跑步
'''

import types

class Person(object):
    num = 0 #num是一个类属性
    def __init__(self, name = None, age = None):
        self.name = name
        self.age = age
    def eat(self):
        print("eat food")

#定义一个类方法
@classmethod    #函数具有cls属性
def testClass(cls):
    cls.num = 100
#     类方法对类属性进行修改,使用cls进行修改

#定义一个静态方法
@staticmethod
def testStatic():
    print("---static method----")

P = Person("老王", 24)
#调用在class中的构造方法
P.eat()
#给Person类绑定类方法
Person.testClass = testClass #使用函数名进行引用

#调用类方法
print(Person.num)
Person.testClass()#Person.testClass相当于testClass方法
print(Person.num)#验证添加的类方法是否执行成功,执行成功后num变为100,类方法中使用cls修改的值
#给Person类绑定静态方法
Person.testStatic = testStatic#使用函数名进行引用
#调用静态方法
Person.testStatic()

'''
eat food
0
100
---static method----
'''

2020-05-08

posted @ 2020-05-08 00:53  CodeYaSuo  阅读(585)  评论(0编辑  收藏  举报