python中实例对象添加方法的方式和类中添加类方法,静态方法的方式

import types
class Person(object):

    def __init__(self, newName, newAge):
        self.name = newName
        self.age = newAge
    def eat(self):
        print("————%s正在吃" %self.name)
def run(self): #动态的方法
    print("————%s正在跑" % self.name)
P = Person("p2",20)
p1 = Person("p1",10)
p1.eat()
# p1.run = run
# p1.run()
# #虽然p1对象中run属性已经指向了第八行的函数,但是这句代码还不正确。
# #因为run属性指向的函数是后来添加的,即p1.run()的时候,并没有把p1当做一个参数,
# #导致了第八行的函数调用的时候,出现且少参数的问题。

#实例对象添加方法的方式:以下两种都可以,一般使用第一种即p1.run = types.MethodType(run.p1) , p1.run() 这种方便找到外部的动态方法
# p1.run = types.MethodType(run,p1) #将函数run,添加到p1的对象里面。对象里添加函数的方法。
# p1.run()
xxx = types.MethodType(run,p1)
'''
相当于
def eat(self):  def eat(p1):
将p1对象定位到self

'''
xxx()


@staticmethod
def test(): #静态方法。
    print("---------static method--------------")

Person.test = test #给类属性添加静态的方法,添加的时候是把类属性里面添加静态的方法,里面的属性名,指向了外面的静态方法
Person.test() #直接使用类.类的属性访问外部添加的静态方法。实际是Person.test指向了外部定义的静态方法test()


@classmethod
def printNum(cls): #定义一个类的方法。
    print("-----------class method-----------------")


#将类的方法添加到类属性里面去。
Person.printNum = printNum  #将类的属性指向了外部的类属性printNUm,其中的Person.printNum中的printNum的名字可以自己命名,这里取相同的名字只是为了便于记忆外部的方法。
Person.printNum() #执行方法


执行的结果:

————p1正在吃
————p1正在跑 #实例对象添加动态方法
———static method————–  #使用类进行添加静态的方法。
———–class method—————– #类添加类的方法

Process finished with exit code 0

    原文作者:竹叶根
    原文地址: https://blog.csdn.net/qq_29767317/article/details/80758922
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞