Last active
December 2, 2021 00:49
-
-
Save Varriount/837e80da9242a4779c206c96714aa858 to your computer and use it in GitHub Desktop.
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
from dataclasses import dataclass, fields, asdict | |
from json import dumps | |
@dataclass | |
class Foo: | |
a: int | |
b: str | |
@dataclass | |
class Bar: | |
c: float | |
d: list | |
@dataclass | |
class Bin(Foo, Bar): | |
def __init__(self, foo_data: Foo, bar_data: Bar): | |
""" | |
If given, the first argument of `super` specifies where in the class's method resolution | |
order a search for methods and attributes should start. The search will start *after* the | |
type given. | |
Here, the method resolution order is: | |
Bin -> Foo -> Bar -> object | |
Thus: | |
- To call `Foo.__init__`, we pass `Bin` as the first argument, because `Bin` is right | |
before `Foo` in the method resolution order. | |
- To call `Bar.__init__`, we pass `Foo` as the first argument, because `Foo` is right | |
before `Bar` in the method resolution order. | |
Of course, you could also just call `Foo.__init__` and `Bar.__init__` directly too. | |
""" | |
super(Bin, self).__init__(**{field.name: getattr(foo_data, field.name) for field in fields(instance)}) | |
super(Foo, self).__init__(**{field.name: getattr(bar_data, field.name) for field in fields(instance)}) | |
baz: list # Required so that `baz` is included in `asdict`, `repr`, etc. | |
@property | |
def baz(self): | |
return [self.a, self.b, self.c, self.d] | |
if __name__ == "__main__": | |
foo = Foo(1, "two") | |
bar = Bar(3.0, ["four"]) | |
bin = Bin(foo, bar) | |
print("Representation of bin:", repr(bin)) | |
print("Dict of bin:", dumps(asdict(bin), indent=4)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment