在运行init之前,我尝试更改参数,但它没有更改,并且保持为主中给出的第一个参数,如何更改新的中的参数?你知道吗
class A(object):
def __init__(self,ip,st):
print 'A arrived to init '+st
self.ip=ip
def __new__(cls,ip,st):
print "A arrived to new"
if ip>10:
return object.__new__(cls,ip,"A")
while True:
s=input("input?")
a=A(s,"a")
print type(a)
输出:
input?88
A arrived to new
A arrived to init a
<class '__main__.A'>
input?44
A arrived to new
A arrived to init a
<class '__main__.A'>
input?22
A arrived to new
A arrived to init a
<class '__main__.A'>
input?12
A arrived to new
A arrived to init a
<class '__main__.A'>
它是元类的
__call__()
方法,每次传递它接收到的参数时都调用YourClass.__new__()
和YourClass.__init__()
。因此,如果要在参数到达YourClass.__init__()
之前更改参数,有两种解决方案:修饰__init__()
或使用自定义元类重写type.__call__()
。你知道吗(Q&D)装饰器版本:
(Q&D)元类版本(py 2.7.x):
但正如Rawing在评论中正确地提到的那样,您可以直接在类
__init__
方法中执行此操作。你知道吗相关问题 更多 >
编程相关推荐