python元类:type和metaclass

python元类:type和metaclass

  • python中一切皆对象,所以类本身也是对象。类有创建对象的能力,那谁来创建类的呢?答案是type。

1.用tpye函数创建一个类

class A(object):
    pass

# 类名 = tpye(类名-str,父类-tuple,属性-dict)
#此条命令创建类相当于上个class创建类,效果是一样的。
B = type('B', (object,), {})

print(A)
print(B)

输出结果:

<class '__main__.A'>
<class '__main__.B'>
  • 有没有发现输出的结果是一样的。type创建出来的和class定义的都是类。

2.定义带有属性的类:

>>> class Foo(object):
…       bar = True

#相当于:
>>> Foo = type("Foo", (object), {'bar':True})


3.定义带有方法的类:

class Dog(object):
    def bark(self):
        print('wang wang ..')

    @classmethod
    def eat(self):
        print('i am eating...')

# ----------------------------
# 上面创建的类可以用type实现,就相当于:
def bark(self):
    print('wang wang ..')

# @staticmethod也是这样用
@classmethod  
def eat(self):
    print('i am eating...')

Dog = type('Dog', (object,), {'bark': bark, 'eat': eat})

# -----------------------------
# 来试验一下:
dog = Dog()
dog.eat()
dog.bark()

输出结果:

i am eating...
wang wang ..

4.__metaclass__自定义元类:

  • python3中:
def say_hello(self):
    print('hello, I am ' + str(self))


def my_type(class_name, class_fathers, class_attr):
    class_attr['say_hello'] = say_hello  # 给属性列表中加入say_hello
    return type(class_name, class_fathers, class_attr)


class Foo(object, metaclass=my_type):  # 用指定的元类来创建类(python3中需要这样用metaclass)
    pass

print(Foo)

a = Foo()
print(a)
a.say_hello()  # Foo对象拥有了say_hello的方法

  • python2中:
def say_hello(self):
    print('hello, I am ' + str(self))


def my_type(class_name, class_fathers, class_attr):
    class_attr['say_hello'] = say_hello  # 给属性列表中加入say_hello
    return type(class_name, class_fathers, class_attr)


class Foo(object):  # 用指定的元类来创建类
    __metaclass__ = my_type   # (python2中需要这样用metaclass)

print(Foo)

a = Foo()
print(a)
a.say_hello()  # Foo对象拥有了say_hello的方法

  • metaclass可以用来给类做一些初始化(可以继承父类,没谁用这个)。其实metaclass一般情况下没什么用,但了解了总算是更加了解了python的底层。

posted @ 2017-04-03 20:03  王辉辉的猫  阅读(484)  评论(0编辑  收藏  举报