-
-
Save byteface/6e35bba23cf4ec78a48a8dea7621615c to your computer and use it in GitHub Desktop.
Quick demonstration of `__slots__` with inheritance. Subclasses are able to make their own independent decision on whether to use slots or not. Subclasses will use a dynamic `__dict__` instead of the static `__slots__` as usual, even if their parent class uses `__slots__`.
This file contains hidden or 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
class Foo: | |
__slots__ = ["spam", "eggs"] | |
def __init__(self) -> None: | |
self.spam = "spam" | |
self.eggs = "eggs" | |
class Bar(Foo): | |
def __init__(self): | |
super().__init__() | |
self.bar = "bar" | |
self.eggs = "yum" | |
self.spam = "gross" | |
foo = Foo() | |
bar = Bar() | |
print(foo.spam, foo.eggs) | |
# spam eggs | |
print(bar.spam, bar.eggs, bar.bar) | |
# gross yum bar | |
bar.dynamic_attribute = "works" | |
print(bar.dynamic_attribute) | |
# works | |
foo.dynamic_attribute = "doesn't work" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment