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)

  • 相关阅读:
    一些简单的逻辑题
    3种数据类型之间的转换
    搭建selenium + Python环境的总结:
    杂记
    Eclemma的安装
    LR----实现WebService测试
    LR--实现HTTP协议的接口测试
    Loadrunner---解决乱码问题
    selenium常用API实例
    JMeter中响应数据显示乱码问题解决
  • 原文地址:https://www.cnblogs.com/anhao-world/p/13325348.html
Copyright © 2011-2022 走看看