Python 如何在抽象类中调用非抽象方法?
我在python中有一个抽象类,希望在其中调用非抽象方法。有可能吗Python 如何在抽象类中调用非抽象方法?,python,abstract-class,Python,Abstract Class,我在python中有一个抽象类,希望在其中调用非抽象方法。有可能吗 from abc import ABC, abstractmethod class MyAbstract(ABC): # Can I call method get_state() from get_current() ? def get_state(): get_current() # gives me error? def get_current(): @abstractmethod def get_time(
from abc import ABC, abstractmethod
class MyAbstract(ABC):
# Can I call method get_state() from get_current() ?
def get_state():
get_current() # gives me error?
def get_current():
@abstractmethod
def get_time():
我有另一个python文件Temp.py来实现这个接口。
在Temp.py中,我使用MyAbstract.get_state()
调用get_state
,得到一个错误,指出get_current()
未定义
不知道为什么
非常感谢您的帮助。一般来说,所有方法都有一个名称空间,即它们所附加到的类或对象。如果您有一个类的实例四处浮动(例如,大多数情况下,
self
),则可以在该实例上调用方法,该方法会自动将实例本身作为第一个参数传递—该实例充当实例方法的命名空间
如果您使用的是类方法或静态方法,那么名称空间几乎总是它们所附加到的类。如果您没有指定名称空间,那么python假定您试图调用的任何函数都在全局名称空间中,如果不是,那么您将得到一个namererror
在这种情况下,以下各项应适用于您:
class MyAbstract(ABC):
def get_current():
print("current")
def get_state():
MyAbstract.get_current()
@abstractmethod
def get_time():
pass
您可以想象,您在get_current()
上方挂着一个不可见的@staticmethod
装饰器,将其标记为这样。问题是,现在您无法更改子类中get\u current()
的行为来影响get\u state()
中的更改。解决方法是将get\u state()
作为类方法:
@classmethod
def get_state(cls):
cls.get_current()
调用静态方法使用与调用类方法相同的语法(在这两种情况下,您都会执行
MyAbstract.get_state()
,但后者会将您正在调用的类作为第一个参数传递。然后,您可以将该类用作命名空间来查找方法get_current()
对于最近定义它的任何子类,这就是如何使用静态方法实现多态性。请正确缩进代码,并在帖子中包含完整的回溯get\u current
未定义,至少不在get\u state
的范围内。