Python “protected” attributes

后端 未结 7 1324
迷失自我
迷失自我 2020-12-13 03:39

How do I access a private attribute of a parent class from a subclass (without making it public)?

7条回答
  •  北海茫月
    2020-12-13 04:29

    No one seems to answer the original question

    how to access a private attribute of a parent class from a subclass

    So here's a simple use case, demonstrating two options - accessing parent class __private variables and using @property decorator:

    class Family:
    
        def __init__(self, name):
            self.__family_name = name
    
        @property
        def name(self):
            return self.__family_name
    
    
    class Child(Family):
    
        def __init__(self, first_name, last_name):
            super(Child, self).__init__(last_name)
            self.__child_name = first_name
    
    
        @property
        def name(self):
            return (self.__child_name, super(Child, self).name)
    
    
    if __name__ == '__main__':
        my_child = Child("Albert", "Einstein")
    
        # print (my_child.__child_name)         # AttributeError - trying to access private attribute '__child_name'
        # print (my_child.__family_name)        # AttributeError - trying to access private attribute '__family_name'
        print (my_child._Child__child_name)     # Prints "Albert" - By accessing __child_name of Child sub-class
        print (my_child._Family__family_name)   # Prints "Einstein" - By accessing __family_name in Family super-class
        print (" ".join(my_child.name))         # Prints "Albert Einstein" - By using @property decorators in Child and Family 
    

提交回复
热议问题