Skip to content

Instantly share code, notes, and snippets.

@Varriount
Last active December 2, 2021 00:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Varriount/837e80da9242a4779c206c96714aa858 to your computer and use it in GitHub Desktop.
Save Varriount/837e80da9242a4779c206c96714aa858 to your computer and use it in GitHub Desktop.
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