# class A(object): python2 必须显示地继承object class A: def __init__(self): print("__init__ ") super(A, self).__init__() def __new__(cls): print("__new__ ") return super(A, cls).__new__(cls) def __call__(self): # 可以定义任意参数 print('__call__ ') A()
__new__ __init__
def __init__(self): print("__init__ ") print(self) super(A, self).__init__() def __new__(cls): print("__new__ ") self = super(A, cls).__new__(cls) print(self) return self
__new__ <__main__.A object at 0x1007a95f8> __init__ <__main__.A object at 0x1007a95f8>
def __init__(self, a, b): self.a = a self.b = b super(A, self).__init__()
class B: def __init__(self, *args, **kwargs): print("init", args, kwargs) def __new__(cls, *args, **kwargs): print("new", args, kwargs) return super().__new__(cls) B(1, 2, 3) #输出 new (1, 2, 3) {} init (1, 2, 3) {}
class BaseController(object): _singleton = None def __new__(cls, *a, **k): if not cls._singleton: cls._singleton = object.__new__(cls, *a, **k) return cls._singleton
a = A() print(callable(a)) # True
class Counter: def __init__(self, func): self.func = func self.count = 0 def __call__(self, *args, **kwargs): self.count += 1 return self.func(*args, **kwargs) @Counter def foo(): pass for i in range(10): foo() print(foo.count) # 10
在 Bottle 中也有 call 方法 的使用案例,另外,stackoverflow 也有一些关于 call 的实践例子,推荐看看,如果你的项目中,需要更加抽象化、框架代码,那么这些高级特性往往能发挥出它作用。
总结
以上就是关于python中的__init__与__new__以及__call__三个方法的简单介绍的详细内容,更多请关注Gxl网其它相关文章!
查看更多关于关于python中的__init__与__new__以及__call__三个方法的简单介绍的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did84686