python3__面向对象__类的起源(type)

版权声明:本文为博主原创文章,未经博主允许不得转载,希望能在相互交流中共同成长。【大红色:一级标题 绿色:二级标题 二红色:三级标题 黄色:四级标题】 https://blog.csdn.net/admin_maxin/article/details/84025255

1.一切皆对象

python中有一个重要的概念那就是一切皆对象;一切都可以赋值给变量(引用)

①内置类型赋值

②将类类型赋值给变量

③将函数赋值给变量

④将自定义类赋值给变量

class Foo(object):
    def __init__(self, name):
        self.name = name


if "__main__" == __name__:

    a = 1
    print(type(a))  # <class 'int'>
    a = "123"
    print(type(a))  # <class 'str'>
    a = int
    str = "123"
    print(type(str), type(a(str)))  # <class 'str'> <class 'int'>
    a = Foo
    f = a("maxin")
    print(f.name)  # maxin

2.类的起源

在1中可知,python中一切皆对象,那么f是由Foo类实例化所得,那Foo这个对象是由那个类实例化所得的那?Type

类名 = type("类名", (当前类的基类, ), 类成员字典)

那问题来了?type类中是如何创建类的?恰巧__metaclass__表示的是该类由谁来实例化创建,因此可借助于type类的派生类来查看类的创建过程。

class MyType(type):
    def __init__(self, what, bases=None, dict=None):
        print("MyType __init__")
        super(MyType, self).__init__(what, bases, dict)

    def __call__(self, *args, **kwargs):
        print("MyType __call__")
        obj = self.__new__(self, *args, **kwargs)
        self.__init__(obj, *args, **kwargs)



class Foo(object):
    # __metaclass__: 表示该类是由谁来实例化创建的
    __metaclass__ = MyType

    def __init__(self, name):
        self.name = name
        print("Foo __init__")

    def __new__(cls, *args, **kwargs):
        print("Foo __new__")
        return object.__new__(cls)


if "__main__" == __name__:

    obj = Foo("maxin")
    print(obj.name)
    print(Foo.__metaclass__)  # <class '__main__.MyType'>
    # python3
    # Foo __new__ / Foo __init__ / maxin
    # python2
    # MyType __init__ / MyType __call__ / Foo __new__ / Foo __init__

猜你喜欢

转载自blog.csdn.net/admin_maxin/article/details/84025255