从父母那里获取父母的功能

时间:2016-08-25 11:11:47

标签: python python-3.x inheritance

我覆盖了一个函数,但希望从父文件中获取父函数。

>>> class a:
...     def __init__(self):
...             print(self.f)
...     def f(self):
...             pass
...
>>> class b(a):
...     def __init__(self):
...             super(b, self).__init__()
...     def f(self):
...             pass
...
>>> b()
<bound method b.f of <__main__.b object at 0x000002E297A96160>>

我希望打印输出a.f

2 个答案:

答案 0 :(得分:1)

您可以使用name manglingself.__fA.__f的班级定义中引用A

  

名称修改有助于让子类覆盖方法而不破坏类内方法调用

class A:

    def __init__(self):
        self.__f()

    def f(self):
        print('A.f')

    __f = f   # Private copy of A's `f` method

class B(A):

    def __init__(self):
        super(B, self).__init__()

    def f(self):
        print('B.f')

b = B()
b.f()

打印

A.f
B.f

答案 1 :(得分:-1)

class a(object):
    def __init__(self):
        pass

    def f(self):
        print 'Parent Method...'

class b(a):
    def __init__(self):
        super(b, self).__init__()
        a.f(self) #referance the parent class rather than the child class, because the child overrides the parent method.
        self.f()

    def f(self):
        print "Childs Method..."


b()