我如何覆盖init?

时间:2013-02-25 19:53:39

标签: python

我有:

Class A:
    def __init__(self, y):
        blah, blah, blah
    def af(self, h):
        print "this"

我像这样骑过defs:

def my_init(self,h):
    gangsta wangsta
def aff(self,h):
    print "that"

A.af = aff # works
A.__init__ = my_init # doesn't work

它不能与init一起使用....如何使用__init__

2 个答案:

答案 0 :(得分:2)

最简单的方法是子类:

class B(A):
     __init__ = my_init

答案 1 :(得分:2)

究竟是什么问题?

>>> class X:
...   def __init__(self):
...     print "Original Init!"
...
>>> def new_init(self):
...    print "OK New Init"
>>> X()
Original Init!
>>> X.__init__ = new_init
>>> X()
OK New Init