Python class attributes during definition using functions

1 week ago 2
ARTICLE AD BOX

I need to set class attributes by calling a function during class definition. A very simplified example would look like the following.

class Mammal(): # Base class provided by internal library class Dog(Mammal): set_sound("Woof") class Cat(Mammal): set_sound("Meow")

Where the function set_sound(val) sets a class attribute for the derived class. Later I should be able to programmatically use these class attributes as normal.

print( Dog.sound ) # Woof print( Cat.sound ) # Meow

How is this accomplished?

I've tried to reverse engineer a far more complex piece of code doing this very thing with limited success. I'm not getting it to work properly and ideally I shouldn't have to create an instance to set the attributes:

import functools class DirectiveMeta(): directives_to_be_executed = [] def __init__(self): for directive in self.directives_to_be_executed: directive(self) @staticmethod def directive(): def decorator(decorated_function): @functools.wraps(decorated_function) def wrapper(*args, **kwargs): result = decorated_function(*args, **kwargs) values = (result,) DirectiveMeta.directives_to_be_executed.extend(values) return result return wrapper return decorator class Mammal(DirectiveMeta): def __init__(self): super().__init__() directive = DirectiveMeta.directive @directive() def sound(s): print(f'Inside sound() s = {s}') return lambda pkg: _execute_version(pkg, s) def _execute_version(pkg, s): print(f'Inside _execute_version pkg = {pkg} sound = {s}') pkg.sound = s class Dog(Mammal): sound("Woof") class Cat(Mammal): sound("Meow") if __name__ == '__main__': d = Dog() #c = Cat() #print(Dog.sound)
Read Entire Article