In the project I'm working on, we have a hierarchy of classes with each class defining a get_text()
method.
class Base:
def get_text(self):
raise NotImplementedError
class Derived1(Base):
def get_text(self):
return "Text from Derived1"
class Derived2(Base):
def get_text(self):
return "Text from Derived2"
obj1 = Derived1()
print(obj1.get_text())
==> 'Text from Derived1'
obj2 = Derived2()
print(obj2.get_text())
==> 'Text from Derived2'
This way, the programmer can call obj.get_text()
and get the text from the class obj
is pointing to.
Now I want to refactor the method to be just an attribute (called TEXT
). I want to keep the original methods for backward compatibility, though. Is there a way to do it in the base class only?
class Base:
def get_text(self):
"""
Keep backward compatibility.
"""
return TEXT # What should be here?
class Derived1(Base):
TEXT = "Text from Derived1"
class Derived2(Base):
TEXT = "Text from Derived2"
obj1 = Derived1()
print(obj1.TEXT)
# Non-refactored code
obj2 = Derived2()
print(obj2.get_text())
==> NameError: name 'TEXT' is not defined
Coming from C++, I'm used to having a pointer to the base class invoke a method from the derived class using C++ virtual method dispatching. Is something similar possible in Python?
To answer my own question (thanks to the commenters:) both following ways work:
return self.__class__.TEXT
Here, self.__class__
points either to Derived1
or to Derived2
class objects, which have access to TEXT
.
return self.TEXT
makes this one step shorter, as the attribute resolution algorithm accesses class attributes automatically.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.