为什么不__init__被调用? [英] Why does __init__ not get called?
问题描述
我上周仍在使用我的DateTime课程......
为什么__init__没有被调用?
http://www.python.org /dev/doc/devel/...omization.html
read" if __new __()返回cls的实例,然后新实例'
__init __()方法将被调用并且据我所知,cls非常好
很多日期时间的实例
************
导入日期时间
_datetime = datetime.datetime
class DateTime(_datetime):
""
与内置datetime.datetime相同,但它接受
无效的日期和时间作为输入。
"""
_valid = True
__dict__ = _datetime .__ dict__
def __init __(自我,年,月,日,* args,* * kw):
print" init called"
_valid = False
self.year = year
self.month = month
self.day = day
self.args = args
self.kw = kw
def throwError():
引发ValueError,''无效日期''
for _datetime中的方法.__ dict __。keys():
if method!=''__ doc__'':
setattr(self,method,throwError)
def __new __(cl s,年,月,日,* args,** kw):
打印" new called"
试试:
return _datetime .__ new __(cls,year,month,day,* args,
** kw)
除了ValueError:
return cls
*************
I''m still working on my DateTime class from last week...
Why does __init__ not get called?
The docs at
http://www.python.org/dev/doc/devel/...omization.html
read "If __new__() returns an instance of cls, then the new instance''s
__init__() method will be invoked" and as far as I can tell cls is very
much an instance of DateTime
************
import datetime
_datetime = datetime.datetime
class DateTime(_datetime):
"""
Identical to builtin datetime.datetime, except it accepts
invalid dates and times as input.
"""
_valid = True
__dict__ = _datetime.__dict__
def __init__(self, year, month, day, *args, **kw):
print "init called"
_valid = False
self.year = year
self.month = month
self.day = day
self.args = args
self.kw = kw
def throwError():
raise ValueError, ''Invalid Date''
for method in _datetime.__dict__.keys():
if method!=''__doc__'':
setattr(self, method, throwError)
def __new__(cls, year, month, day, *args, **kw):
print "new called"
try:
return _datetime.__new__(cls, year, month, day, *args,
**kw)
except ValueError:
return cls
*************
推荐答案
呃...你真的吗?试图实例化这个类?
mydate = DateTime(2005,8,8)
我问的原因是__init__ /是/在我运行你的代码时调用
Python 2.4,前提是上面的行添加到最后。
Uh... are you actually trying to instantiate this class?
mydate = DateTime(2005, 8, 8)
The reason I ask is that __init__ /is/ called when I run your code on
Python 2.4, provided that the above line is added to the end.
啊ok ,那很有意思我还没有尝试过有效的约会。现在怎样
当我传递一个无效的日期时我会调用__init__并且
抛出ValueError并在__new__中捕获。
dt = DateTime(2005,02,30)
Ah ok, thats interesting I hadn''t even tried a valid date yet. Now how
do I get this thing to call __init__ when I pass in an invalid date and
the ValueError is thrown and caught within __new__.
dt = DateTime(2005, 02, 30)
不接受?这是我尝试通过碰撞我自己的
帖子来获得一些关注。
Not takers? This is my attempt to get some attention by bumping my own
post.
这篇关于为什么不__init__被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!