force implementing specific attributes in subclass python

扶醉桌前 提交于 2021-01-07 03:41:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!