I just realized that I can set a property of a child class and only its parent class will use it
In [34]: class A:
...: def __init__(self):
...: pass
...:
...: def a(self):
...: print(f'b = {self.b}')
...:
...: class B(A):
...: def __init__(self):
...: super(B, self).__init__()
...: self.b = 1
...:
In [35]: b = B()
...: b.a()
b = 1
This implementation seems counterintuitive, something feels wrong, but I'm not quite sure what it is
I think the following words make more sense
In [38]: class A:
...: def __init__(self, b):
...: self.b = b
...:
...: def a(self):
...: print(f'b = {self.b}')
...:
...: class B(A):
...: def __init__(self):
...: super(B, self).__init__(1)
...:
In [39]: b = B()
...: b.a()
b = 1
Is there a use case where the former is more recommended than the latter
Conceptually, you're doing two different things. In the first case, you have something like an abstract class; in other words, a base class, which cannot be instantiated on its own due to the "missing" definition of some properties; subclasses will understandably implement these properties
A more idiomatic way is to use abc
modules to A
mark as abstract base classes , for example:
from abc import ABCMeta, abstractmethod
class A(metaclass=ABCMeta):
@property
@abstractmethod
def x(self):
pass
def print_me(self):
print(f'x = {self.x}')
class B(A):
@property
def x(self):
return 1
A().print_me()
Then the output is:
TypeError: Can't instantiate abstract class A with abstract methods x
On the other hand, this works:
B().print_me() # prints x = 1
By doing this, you're clearly showing that subclasses must override x
the property, otherwise print_me
the function won't work
Moving on to the second case, you have a concrete base class and subclasses, the subclasses act like constraints on the nature of the instances that can be created. In this case, A
a standalone instance of is perfectly valid; just B
an instance of a provides the extra guarantee that a particular property will always be some particular value (or, if you want your class to be mutable, then at least initialize it to some specific value)