天天看点

python中的元类、静态方法、类方法,动态添加方法

首先介绍几个概念:

1、#所谓的静态方法就是这个方法任何类都可以调用,程序一加载就存在的方法

2、所谓的类方法就是这个类一加载就存在的方法,不用实例化这个类就已经存在的方法

3、所谓的元类就是创建类的类

元类:

type

我们知道对象是通过构造函数来初始化的,name对象到底是谁创建的呢。其实我们再之前就接触过元类。例如我们创建整形类用int,创建字符串类用str,那么我们创建对象类使用什么来创建的。这里我们就提到了type这个元类。

type

是创建类的元类,就像认识形态领域的元认知是对认知的认知。

举例:

@staticmethod
def run():
    print("runing.......")
def eat(self,food):
    print("eat......."+food)
@classmethod
def smile(cls):
    print("smile.........")

def createObvject():
    p1 = type("Person", (), {"name": "hongbiao", "age": , "run": run,"eat": eat,"smile":smile})
    return p1
if __name__ == '__main__':
    per = createObvject()
    per.smile()
    person = per()
    print(person.name)
    print(person.age)
    print(hasattr(per, "name"))
    person.run()
    person.eat("hhh")
    person.smile()
           

打印结果

smile......... hongbiao 25 True runing....... eat.......hhh smile.........

从上面我们可以得到

type

这个就是元类,通过这个原来来创建对象,

createObvject

里面封装了type,返回一个对象,注意是返回一个对象而不是实例对象。

per()

表示实例化一个对象。

分析type这个方法:

源码如下:
def __init__(cls, what, bases=None, dict=None): # known special case of type.__init__
        """
        type(object_or_name, bases, dict)
        type(object) -> the object's type
        type(name, bases, dict) -> a new type
        # (copied from class doc)
        """
        pass
           
type接收三个参数,分别是对象名称,继承内容也就是一般类后面的括号,第三个参数是一个字典类型,用来存贮属性。

这里的属性分为一般属性,静态属性,和类属性

静态属性需要使用装饰器

staticmethod

修饰,而类属性需要用

classmethod

来修饰

python动态添加方法

python 作为一门动态的语言,可以在代码执行的过程中来添加方法
def run(self):
    print("running..........")

import types
class Person(object):
    def __init__(self, name=None,age=None):
        this.name = name
        this.age = age
    def eat(self):
        print("eat...........")
p = Person("hb", )
p.eat()#正常
p.run()#报错,因为run并不是Person的方法
# 那么我们想添加进去,怎么弄呢
import types
p.run =  types.MethodType(run,p)
# 执行完上面的代码之后下面再调用这个方法就不会报错了
p.run()
# 打印结果:"running.........."