【发布时间】:2021-04-30 05:44:06
【问题描述】:
我正在开发一个使用 Python 中的抽象类(特别是 abc 模块)的项目。
我有几个这个抽象类的实现,都有自己的构造函数,需要使用self。
这是我的代码的样子,但经过简化:
from abc import ABC, abstractmethod
class BaseClass(ABC):
def __init__(self):
self.sublinks = [] # not meant to be passed in, that's why it isn't an argument in __init__
@classmethod
def display(cls):
print(cls.get_contents())
@abstractmethod
def get_contents():
pass
class ImplementationOne(Base):
def __init__(self, url):
self.url = url
def get_contents(self):
return "The url was: " + url
class ImplementationTwo(Base):
def get_contents():
return "This does not need a url"
test_one = ImplementationOne("https://google.com")
test_two = ImplementationTwo()
test_one.display()
但是,当我运行它时,我收到了错误 TypeError: get_contents() missing 1 required positional argument: 'self'。
我认为这是因为 ImplementationOne 中的get_contents() 采用了self,但在抽象方法中没有指定。
所以,如果我改变了:
@abstractmethod
def get_contents():
pass
到
@abstractmethod
def get_contents(self):
pass
但我得到了同样的错误。
我尝试了很多组合,包括将self 作为每次出现的参数或get_contents,并在抽象类中将cls 传递给get_contents - 但没有运气。
那么,我如何才能仅在抽象方法的某些实现中使用self 关键字(也称为访问属性),该方法在抽象类本身的类方法中调用。
另外,附带说明一下,如何在 BaseClass 的所有实现中访问 self.sublinks,同时在每个实现实例中具有不同的值?
【问题讨论】:
-
this 有帮助吗?
标签: python python-3.x class abc python-class