问题
I'm have a parent class, and I would like to "force" everyone that will inherit from it to implement some specific class attributes.
I don't have this problem with methods, since I have created a dummy method that raises NotImplementedError
, which makes it very clear.
As for class attributes- I do not want to create them in the parent class and set them to None since that doesn't force the developer to implement them in the child class.
A little code to demonstrate the current situation:
class Pet(object):
name = None
def make_noise(self):
raise NotImplementedError("Needs to implement in subclass")
def print_my_name(self):
print(self.name)
class Dog(Pet):
# how to force declairing "name" attribute for subclasses?
def make_noise(self):
print("Whof Whof")
In this example, developer 1 created Pet class and wanted other developers to implement subclass with a "name" attribute. Developer2 implemented a subclass, but didn't know he needs implement the "name" attribute.
Is it possible to create such restrictions in python?
回答1:
You can try by using ABCMeta metaclass or ABC. After that you can use the @abstractmethod of an @property. eg:
class Pet(ABC):
@abstractmethod
@property
def name(self)
pass
def make_noise(self):
raise NotImplementedError("Needs to implement in subclass")
def print_my_name(self):
print(self.name)
With this you can add a setter as well with @name.setter
.
回答2:
use can use python's Abstract Base Class
/ ABS
or Method Overriding
whichever is feasible for you as per your requirements.
来源:https://stackoverflow.com/questions/59285990/force-implementing-specific-attributes-in-subclass-python