I'm working on a project using abstract classes in Python (specifically, the abc module).
I have a few implementations of this abstract class, which have their own constructors and need to use self
.
This is what my code looks like, but simplified:
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()
When I run this, however, I get the error TypeError: get_contents() missing 1 required positional argument: 'self'
.
I figured that this is because get_contents()
in ImplementationOne takes self
, but it's not specified in the abstract method.
So, if I changed:
@abstractmethod
def get_contents():
pass
to
@abstractmethod
def get_contents(self):
pass
But I get the same error.
I've tried many combinations, including putting self
as an argument to every occurrence or get_contents
, and passing in cls
to get_contents
in the abstract class - but no luck.
So, pretty much, how can I use the self
keyword (aka access attributes) in only some implementations of an abstract method, that's called within a class method in the abstract class itself.
Also, on a side note, how can I access self.sublinks
from within all implementations of BaseClass, while having its values different in each instance of an implementation?