python:在父类的方法中,调用该类的classmethod,但绑定到子类

时间:2011-09-23 18:09:53

标签: python inheritance attributes class-method

说我有以下代码:

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()

Parent.__init__中,我需要调用在Parent中定义的'foo',但我需要调用它绑定到Child,以便访问cls.classattr1实际上将访问该属性,因为它在Child中被覆盖。任何想法如何做到这一点?

3 个答案:

答案 0 :(得分:1)

这是一个选项:

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()不再是类方法,但最终结果应与您想要的结果相同。

>>> 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

答案 1 :(得分:0)

这应该有效:

Parent.foo.im_func(Child)

但看起来有点邪恶。

答案 2 :(得分:0)

您真的需要foo成为classmethod吗?如果没有,这可行。:

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'