父类从子类调用私有属性

2024-03-29 11:49:35 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的示例中,最后一行B().show()没有调用适当版本的show函数。它应该调用子版本而不是父版本。我想我应该做一些类似于\uuu类\u方法()的事情,但却找不出一个完整的答案。你知道吗

我当然可以覆盖B中的show函数,但这实际上意味着复制和粘贴show函数。它不优雅。你知道吗

## version one ##
class A(object):

    def method(self):
        print("hello")

    def show(self):
        self.method()

class B(A):

    def method(self):
        print("goodbye")


A().show() ## print out hello
B().show() ## print out goodbye

## version two ##    
class A(object):

    def __method(self):
        print("hello")

    def show(self):
        self.__method()

class B(A):

    def __method(self):
        print("goodbye")


A().show() ## print out hello
B().show() ## print out hello

Tags: 函数self版本示例helloobjectversiondef
2条回答

如果您用两个下划线开始一个方法名,它将使它只能从该类访问。考虑以下示例:

class A():
    def __m(self):
        pass
    def m(self):
        print(self.__m)

A().m()  # <bound method A.__m of <__main__.A object at 0x10e0c1898>>
A().__m()  # AttributeError: 'A' object has no attribute '__m'

那么A().__m怎么了?查看A.__dict__,在这里可以查找属性:

>>> A.__dict__
mappingproxy({'__module__': '__main__', '_A__m': <function A.__m at 0x10e0ab730>, 'm': <function A.m at 0x10e0ab7b8>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None})

最重要的是:

'_A__m': <function A.__m at 0x10e0ab730>

因此,您编写的函数__m被重命名为_A__m。您不能从类之外的任何地方访问这些方法。你知道吗

如果类中有一个方法show调用一个方法__method(以__开头),它将只调用该类的该方法,因为它永远不知道_B__method,只知道_A__method。你知道吗

请注意,绝对不应该使用_A__method从类外部调用此方法。如果你需要做你正在做的事情,你应该用一个下划线。你知道吗

如果您真的需要B__method方法是私有的,那么B也应该重写show

class A(object):
    def __method(self):
        print("hello")
    def show(self):
        self.__method()

class B(A):
    def __method(self):
        print("goodbye")
    def show(self):
        self.__method()

A().show() ## print out hello
B().show() ## print out goodbye

要保留每个类的私有方法并能够访问它们,可以执行以下操作:

class A(object):

    def __method(self):
        print("hello")
    method = __method

    def show(self):
        self.method()


class B(A):

    def __method(self):
        print("goodbye")
    method = __method

输出:

hello
goodbye

相关问题 更多 >