Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python Encapsulation
#3
Explanation:

Base Class:
  • BaseClass defines a constructor (__init__) that initializes a private attribute _x with the value 10. The underscore (_) in front of _x indicates it's intended for internal use within the class and shouldn't be directly access from outside.
Derived Class:
  • DerivedClass inherits from BaseClass.

  • Its constructor (__init__) explicitly calls the base class constructor using super().__init__(). This ensures that the base class's initialization logic is executed first.

  • It then prints the value of self._x. However, due to name mangling (Python's way of protecting private attributes in subclasses), directly accessing _x would result in an AttributeError. To access the private attribute from the base class, it's recommended to use protected methods or properties defined in the base class itself.

Output:

Since _x is private, attempting to print obj2.x in the original code would cause an AttributeError. Here's the corrected output:
10
This output is produced because the print(self._x) line in DerivedClass's constructor is able to access the private attribute within the derived class instance.
buran write Apr-02-2024, 06:02 PM:
Spam link removed
Reply


Messages In This Thread
Python Encapsulation - by codinglearner - Mar-24-2022, 12:47 PM
RE: Python Encapsulation - by deanhystad - Mar-24-2022, 07:26 PM
RE: Python Encapsulation - by DataScience - Apr-02-2024, 01:26 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Function encapsulation Oldman45 4 2,345 Jan-22-2021, 11:38 AM
Last Post: Oldman45
  Preserve Encapsulation while Displaying Information QueenSvetlana 13 7,108 Dec-07-2017, 06:13 PM
Last Post: snippsat
  Encapsulation issue iFunKtion 4 4,006 Mar-07-2017, 10:13 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020