面向对象的一些补充(type创建类,__mro__)

__mro__,找到当前类寻找属性的顺序

复制代码
class A(object):
    pass


class B(A):
    pass


class C(object):
    pass

class D(B,C):
    pass

print(D.__mro__)
复制代码

__dict__

获取当前类的所有属性

复制代码
class Foo(object):
    CITY = 'bj'
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def func(self):
        pass

# print(Foo.CITY)
# print(Foo.func)
print(Foo.__dict__)

obj1 = Foo('oldboy',54)
print(obj1.__dict__)
复制代码

__dict__获取的是一个字典,还可以通过dir获取字典的键

metaclass

1. 创建类的两种方式

复制代码
class Foo(object):
    CITY = "bj"

    def func(self,x):
        return x + 1

Foo = type('Foo',(object,),{'CITY':'bj','func':lambda self,x:x+1})
复制代码

2. 类由自定义type创建

类由type创建,通过metaclass可以指定当前类由那一个type创建,默认为type类

复制代码
class MyType(type):
    def __init__(self,*args,**kwargs):
        print('创建类之前')
        super(MyType,self).__init__(*args,**kwargs)
        print('创建类之后')

class Foo(object,metaclass=MyType): # 当前类,由type类创建。
    CITY = "bj"
    def func(self, x):
        return x + 1
复制代码

3. 类的继承

类的基类中指定了metaclass,那么当前类也是由metaclass指定的类来创建当前类

复制代码
class MyType(type):
    def __init__(self,*args,**kwargs):
        print('创建类之前')
        super(MyType,self).__init__(*args,**kwargs)
        print('创建类之后')

class Foo(object,metaclass=MyType): # 当前类,由type类创建。
    CITY = "bj"
    def func(self, x):
        return x + 1

class Bar(Foo):
    pass
复制代码

Bar也使有MyType创建的

其它形式

复制代码
# ################################## 变 ##################################
"""
class MyType(type):
    def __init__(self,*args,**kwargs):
        print('创建类之前')
        super(MyType,self).__init__(*args,**kwargs)
        print('创建类之后')

Base = MyType('Base',(object,),{})
# class Base(object,metaclass=MyType):
#     pass

class Foo(Base):
    CITY = "bj"
    def func(self, x):
        return x + 1
"""
# ################################## 变 ##################################
"""
class MyType(type):
    def __init__(self,*args,**kwargs):
        print('创建类之前')
        super(MyType,self).__init__(*args,**kwargs)
        print('创建类之后')

def with_metaclass(arg):
    return MyType('Base',(arg,),{}) # class Base(object,metaclass=MyType): pass

class Foo(with_metaclass(object)):
    CITY = "bj"
    def func(self, x):
        return x + 1
"""
复制代码

类实例化的过程

复制代码
class MyType(type):
    def __init__(self,*args,**kwargs):
        super(MyType,self).__init__(*args,**kwargs)

class Foo(object,metaclass=MyType): # 当前类,由type类创建。
    pass


"""
0. Mytype的__init__
obj = Foo() 
1. MyType的__call__
2. Foo的__new__
3. Foo的__init__
"""
复制代码

总结

1. 默认类由type实例化创建。
2. 某个类指定metaclass=MyType,那么当前类的所有派生类都由于MyType创建。
3. 实例化对象的顺序
  - type.__init__ 
  - type.__call__
  - 类.__new__
  - 类.__init__

原文地址:https://www.cnblogs.com/xyhh/p/10834360.html