Last active
July 29, 2023 01:56
-
-
Save eusoubrasileiro/32c891c81503e63a9facaf6f90e382f9 to your computer and use it in GitHub Desktop.
Decorator to create @Property getters for all my class instance attributes whose names start with one underscore Python3+
This file contains 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
def auto_property_getters(cls): | |
class AutoPropertyClass(cls): | |
def __init__(self, *args, **kwargs): | |
super().__init__(*args, **kwargs) | |
def __getattr__(self, name): | |
if name in [attr[1:] for attr in dir(self) if attr.startswith('_') and not attr.startswith('__')]: | |
return getattr(self, f"_{name}") | |
raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") | |
return AutoPropertyClass | |
@auto_property_getters | |
class X: | |
def __init__(self): | |
self._age = 34 | |
self._address = 'some address' | |
self.dog_name = 'Saitama' | |
Solution 2. | |
class AutoPropertyDecorator: | |
def __init__(self, attr_name): | |
self.attr_name = attr_name | |
def __get__(self, instance, owner): | |
if instance is None: | |
return self | |
return getattr(instance, f"{self.attr_name}") | |
def auto_property_getters(cls): | |
class AutoPropertyClass(cls): | |
def __init__(self, *args, **kwargs): | |
super().__init__(*args, **kwargs) | |
for attr_name in vars(self): | |
if attr_name.startswith('_') and not attr_name.startswith('__') and not isinstance(getattr(self, attr_name), property): | |
setattr(self.__class__, attr_name[1:], AutoPropertyDecorator(attr_name)) | |
return AutoPropertyClass | |
@AutoPropertyDecorator | |
class X: | |
def __init__(self): | |
self._age = 34 | |
self._address = 'some address' | |
self.dog_name = 'Saitama' | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment