设为首页 加入收藏

TOP

Python 类的祖宗--metaclass
2018-10-19 16:51:03 】 浏览:28
Tags:Python 祖宗 --metaclass

1.Python 中一切事物都是对象
2.类都是 type 类的对象

类的两种申明方法

# 方法一:
class Foo:
    def func(self):
        print(666)

obj = Foo()
obj.func()

# 方法二:
def function(self):
    print(777)

Foo = type('Foo', (object,), {'func': function})
#type第一个参数:类名
#type第二个参数:当前类的基类
#type第三个参数:类的成员

obj = Foo()
obj.func()

运行结果:
666
777
class MyType(type):
    def __init__(self, *args, **kwargs):
        print(666)

    def __call__(self, *args, **kwargs):
        print(777)


class Foo(object,metaclass=MyType):
    def func(self):
        print('hello klvchen')

obj = Foo()

运行结果:
666
777
class MyType(type):
    def __init__(self, *args, **kwargs):
        print(666)

    def __call__(self, *args, **kwargs):
        r = self.__new__(self)


class Foo(object,metaclass=MyType):
    def __init__(self):
        pass

    def __new__(cls, *args, **kwargs):
        return '对象'

    def func(self):
        print('hello klvchen')

obj = Foo()

运行结果:
666

创建对象时,调用__init__()方法的过程

参考 https://www.cnblogs.com/wupeiqi/p/4766801.html

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Python 类的特殊成员介绍 下一篇Python 单例设计模式

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目