zoukankan      html  css  js  c++  java
  • python面向对象--元类

    一个类没有声明自己的元类,默认他的元类就是type,除了使用内置元类type,我们也可以通过继承type来自定义元类,然后使用metaclass关键字参数为一个类指定元类
    class Foo:
        def __init__(self):
            pass
    
    f1=Foo()#f1是通过Foo实例化的对象
    
    #print(type(f1))
    print(type(Foo))
    print(Foo.__dict__)
    
    def __init__(self,name,age):
        self.name=name
        self.age=age
    
    Ffo=type("Ffo",(object,),{'x':1,"__init__":__init__})
    print(Ffo)
    print(Ffo.__dict__)
    
    f1=Ffo("alex",20)
    print(f1.__dict__)
    print(f1.name)

    #自定制元类
    class MyType(type):
    def __init__(self,a,b,c):
    print("元类的函数执行")
    print(self)
    # print(a)
    # print(b)
    # print(c)

    #__call__对象后面加括号,触发执行。注:构造方法的执行是由创建对象触发的,即:对象 = 类名() ;而对于 __call__ 方法的执行是由对象后加括号触发的,即:对象() 或者 类()()
        def __call__(self, *args, **kwargs):
    print("=======>")
    print(args,kwargs)
    obj=object.__new__(self)#----->f1生成对象
    self.__init__(obj,*args)
    return obj

    class Foo(metaclass=MyType):# Foo=MyType(4个参数) -->__init__ --->MyType(Foo,'Foo',(object,),{})
    def __init__(self,name):
    self.name=name

    print(Foo)

    f1=Foo("alex")#Foo()执行对象的call方法
    print(f1.name)
    # print(f1.name)
    # print(f1.__dict__)



    如果我失败了,至少我尝试过,不会因为痛失机会而后悔
  • 相关阅读:
    自定义组件要加@click方法
    绑定样式
    647. Palindromic Substrings
    215. Kth Largest Element in an Array
    448. Find All Numbers Disappeared in an Array
    287. Find the Duplicate Number
    283. Move Zeroes
    234. Palindrome Linked List
    202. Happy Number
    217. Contains Duplicate
  • 原文地址:https://www.cnblogs.com/tangcode/p/11484297.html
Copyright © 2011-2022 走看看