My study of the `@delegates` decorator and `GetAttr` from `fastcore`.
I follow https://www.fast.ai/posts/2019-08-06-delegation.html
class Person: def __init__(self, name, age): self.name = name self.age = age class Student(Person): def __init__(self, name, age, grade): super().__init__(name, age) self.grade = grade
student = Student("Alice", 12, 'A') print(student.name, student.age, student.grade)
kid = Student("Uma", 5.5, 'Good Kid!') print(kid.name, kid.age, kid.grade)
%pip install fastcore
from fastcore.meta import delegates
class Person: def __init__(self, name, age, **kwargs): self.name = name self.age = age @delegates() class Student(Person): def __init__(self, name, age, grade, **kwargs): super().__init__(name, age, **kwargs) self.grade = grade
child = Student("Amira", 6, grade='A', school='XYZ') child.__dict__
from fastcore.basics import GetAttr
class Strawberry(GetAttr): def __init__(self, color, variety): self.color, self.variety = color, variety self.default = color
s = Strawberry('red', 'Pegasus') s.color, s.variety, s.default
[s for s in dir(s) if not s.startswith('_')]
def play(game, player='Daddy', num_players=2): print(f'{player} is playing {game}') play('chess', 'Mehdiya')
@delegates(play) def play_chess(player, speed='blitz', **kwargs): play('chess', player) play_chess('Uma')
print(play_chess.__signature__)
import inspect print(inspect.signature(play_chess))
print(inspect.signature(play))