开发者

python: in parent class's method, call classmethod of that class, but bound to a child class

Say I have the following code:

class Parent(object):
    classattr1 = 'parent'
    def __init__(self):
        Parent.foo()

    @classmethod
    def foo(cls):
        print cls.classattr1

class Child(Parent):
    classattr1 = 'child'

    def foo(cls):
        raise Exception("I shouldn't be here")

Child()

In Parent.__init__, I need to call 'foo' that is defined within Parent, but I need to call it bound to Child, so that accessing cls.classattr1 will actually access the 开发者_Python百科attribute as it is overridden in Child. Any ideas how to do this?


Here is an option:

class Parent(object):
    classattr1 = 'parent'
    def __init__(self):
        Parent.foo(self)

    def foo(self):
        print self.classattr1     # or self.__class__.classattr1

class Child(Parent):
    classattr1 = 'child'
    def foo(cls):
        raise Exception("I shouldn't be here")

Child()

Parent.foo() is not a class method anymore, but the end result should be the same as what you want.

>>> c = Child()    # prints 'child' by calling Parent.foo()
child
>>> c.foo()        # Child.foo() raises an exception
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in foo
Exception: I shouldn't be here


This should work:

Parent.foo.im_func(Child)

but looks kinda evil.


Do you really need foo to be a classmethod? If not, this works.:

class Parent(object):
    classattr1 = 'parent'
    def __init__(self):
        Parent.foo(self)

    def foo(self):
        print self.classattr1

class Child(Parent):
    classattr1 = 'child'
    def foo(self):
        raise AttributeError("Wrong foo!")

Child()  # prints 'child'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜