设为首页 加入收藏

TOP

Python-19-元类
2019-08-04 00:19:35 】 浏览:40
Tags:Python-19-元类

一、定义

元类就是类的类

type是python的一个内建元类

类的两种定义方式

# 定义类的两种方式
class Foo(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

print(Foo)  # <class '__main__.Foo'>


def __init__(self, name, age):
    self.name = name
    self.age = age
def test():
    print('====')

FFo = type('Foo', (object,), {'x': 1, '__init__': __init__, 'test': test})
print(FFo)  # <class '__main__.Foo'>
f1 = FFo('alex', 18)
print(f1.__dict__)  # {'name': 'alex', 'age': 18}

二、自定义元类

如果一个类没有声明自己的元类,默认他的元类是type,除了使用元类type,用户也可以自定义元类

class MyType(type):
    def __init__(self, a, b, c):
        print('元类的构造函数开始运行')

    def __call__(self, *args, **kwargs):
        obj = object.__new__(self)
        self.__init__(obj, *args, **kwargs)
        return obj


class Foo(metaclass=MyType):  # Foo = MyType(Foo, 'Foo', (), {})
    def __init__(self, name):
        self.name = name


f1 = Foo('alex')

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Python习题001 下一篇Python学习日记(三) 学习使用dict

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目