zoukankan      html  css  js  c++  java
  • 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)

  • 相关阅读:
    bzoj1861 [Zjoi2006]Book 书架
    bzoj1208 [HNOI2004]宠物收养所
    bzoj1588 [HNOI2002]营业额统计
    bzoj3295 [Cqoi2011]动态逆序对
    bzoj2716 [Violet 3]天使玩偶
    bzoj1176 [Balkan2007]Mokia
    bzoj3262 陌上花开
    spoj FTOUR2
    bzoj2152 聪聪可可
    poj1741 Tree
  • 原文地址:https://www.cnblogs.com/anhao-world/p/13325348.html
Copyright © 2011-2022 走看看