• python type and __mateclass__和__new__的使用


    type:使用type来创建一个类

    def func(self):
    print('%s hello world'%self.name)
    def __init__(self,name ,age):
    self.name = name
    self.age = age


    Foo = type('Foo', (object,), {'test': func,"__init__":__init__})
    # type第一个参数:类名
    # type第二个参数:当前类的基类
    # type第三个参数:类的成员
    f =Foo('test',22)
    f.test()
    print(type(Foo))

    __mateclass__和__new__:

    class MyType(type):
    def __init__(self,*args,**kwargs):
    print("Mytype __init__",*args,**kwargs)

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

    def __new__(cls, *args, **kwargs):
    print("Mytype __new__",*args,**kwargs)
    return type.__new__(cls, *args, **kwargs)

    class Foo(object):
    metaclass = MyType#表示被某个对象创建这个类
    def __init__(self,name):
    self.name = name
    print("Foo __init__")

    def __new__(cls, *args, **kwargs):#通过new来实例化__init__.new是用来创建实例的。
    print("Foo __new__",cls, *args, **kwargs)
    return object.__new__(cls)#继承父亲的__new__方法

    f = Foo("Alex")
    print("f",f)
    print("fname",f.name)

  • 相关阅读:
    [题解] [JSOI2015] 圈地
    [题解] [JSOI2015] 最小表示
    [题解] [JSOI2015] 套娃
    [题解] [JSOI2015] 非诚勿扰
    [题解] [JSOI2015] 送礼物
    [题解] [JSOI2015] 送礼物
    [题解] [JSOI2015] 子集选取
    [题解] [JSOI2015] salesman
    AC自动机学习笔记
    [题解] [JSOI2014] 矩形并
  • 原文地址:https://www.cnblogs.com/anhao-world/p/13325348.html
Copyright © 2020-2023  润新知