所以,我今天才意识到__new__
,从python 2.6开始,对于接收参数已被弃用了(文档中没有提到它,就我所看到的__new__
调用行为而言,这也是不正确的__init__
).这意味着我的功能代码已经开始发出警告,我想摆脱它们.但我看不出一种优雅的解决方法.
我有一堆类在构造时执行优化.所以我有
class Conjunction(Base):
def __new__(cls, a, b):
if a == True:
return b
elif b == True
return a
else:
return super(Conjunction,cls).__new__(cls, a, b)
Run Code Online (Sandbox Code Playgroud)
等等(真实版本涵盖更多案例).因此,与Guido在此响应中所说的不同(我可以找到它的唯一引用),我的__new__
方法确实使用了它的参数,并且不能被重写的__init__
函数替换.
我能做的最好的就是把它分成两部分:
def Conjunction(a, b):
if a == True:
return b
elif b == True
return a
else:
return ConjunctionImpl(a, b)
class ConjunctionImpl(Base):
# ...
Run Code Online (Sandbox Code Playgroud)
但这很丑陋,对高天堂很臭.我是否缺少一种优雅的方法让类构造函数根据给定的构造函数参数返回一些任意对象?
Tho*_*ers 10
__new__
不是"因接收参数而弃用".Python 2.6中的变化是,对象类object.__new__
的__new__
方法不再忽略它传递的任何参数.(也不会再忽略参数,但这只是2.6中的警告.)如果要将参数传递给或,则不能将其用作继承的终止类.object.__init__
object
__new__
__init__
为了使任何代码依赖于这种行为在2.6上班,你只需要更换object
的基类,使用适当的接受额外的参数并没有一个基类不沿着它使调用传递他们(使用super()
).
托马斯在我的回答中把我说得对,但我应该补充一点,在我的案例中解决方案是微不足道的:__new__
在我的基类中添加一个方法:
class Base(object):
def __new__(cls, *args, **kws):
instance = super(Base, cls).__new__(cls)
instance.__init__(*args, **kws)
return instance
Run Code Online (Sandbox Code Playgroud)