Created
January 30, 2020 07:10
-
-
Save janpipek/f75b93001af820444234c6252993f187 to your computer and use it in GitHub Desktop.
Private members in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Jablko: | |
def __init__(self): | |
self.__bar = 123 | |
@staticmethod | |
def show_me(o): | |
print(o.__bar) | |
class IgnorePrivateMembers: | |
def __getattr__(self, name: str): | |
if name.startswith("_") and "__" in name: | |
base_name = name.partition("__")[2] | |
for klass in self.__class__.__mro__: | |
rebranded_name = f"_{klass.__name__}__{base_name}" | |
if rebranded_name in dir(self): | |
return getattr(self, rebranded_name) | |
raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'") | |
class Hruška(IgnorePrivateMembers): | |
# I have _Jablko__bar | |
__bar = "Whiskey Bar" | |
class Švestka(Hruška): | |
pass # I also have _Jablko__bar | |
Jablko.show_me(Švestka()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment