强制在子类python中实现特定属性 [英] force implementing specific attributes in subclass python
问题描述
我有一个父类,我想强迫"所有将从其继承的人来实现某些特定的类属性.
I'm have a parent class, and I would like to "force" everyone that will inherit from it to implement some specific class attributes.
我在方法上没有这个问题,因为我创建了一个引发 NotImplementedError
的伪方法,这很清楚.
I don't have this problem with methods, since I have created a dummy method that raises NotImplementedError
, which makes it very clear.
关于类属性-我不想在父类中创建它们并将它们设置为None,因为这不会迫使开发人员在子类中实现它们.
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")
在此示例中,开发人员1创建了Pet类,并希望其他开发人员实现具有名称"属性的子类.Developer2实现了一个子类,但不知道他需要实现名称"属性.
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.
是否可以在python中创建这样的限制?
Is it possible to create such restrictions in python?
推荐答案
您可以尝试使用 ABCMeta 元类或 ABC 一个>.之后,您可以使用 @abstractmethod href ="https://docs.python.org/3.7/library/functions.html#property" rel ="nofollow noreferrer"> @ property .例如:
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)
与此同时,您也可以使用 @ name.setter
添加设置器.
With this you can add a setter as well with @name.setter
.
这篇关于强制在子类python中实现特定属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!