如何在抽象class中调用非抽象方法?
How to call non abstract method in a abstract class?
我在python中有一个抽象class,想调用其中的非抽象方法。可以吗?
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()
未定义。
不知道为什么。
感谢任何帮助。
通常,所有方法都有一个名称空间,即 class 或它们所附加的对象。如果你有一个 class 的实例浮动(例如 self
,大部分时间),你可以调用该实例上的方法,自动将实例本身作为第一个参数传递 - 实例充当实例方法的命名空间。
如果您使用的是 class 方法或静态方法,那么命名空间几乎总是它们所附加的 class。如果您没有指定名称空间,那么 python 会假设您尝试调用的任何函数都在全局名称空间中,如果不是,那么您会得到一个 NameError
.
在这种情况下,以下内容应该适合您:
class MyAbstract(ABC):
def get_current():
print("current")
def get_state():
MyAbstract.get_current()
@abstractmethod
def get_time():
pass
你可以想象你有一个小的不可见的 @staticmethod
装饰器挂在 get_current()
上面标记它。这样做的问题是,现在您无法更改子 class 中 get_current()
的行为来影响 get_state()
中的更改。解决方案是使 get_state()
成为 class 方法:
@classmethod
def get_state(cls):
cls.get_current()
调用静态方法使用与调用 class 方法相同的语法(在这两种情况下您都可以使用 MyAbstract.get_state()
,但后者通过 class 您'将其作为第一个参数调用 。然后您可以使用此 class 作为名称空间来查找方法 get_current()
用于任何子 class 最近定义的方法,这就是您如何使用静态方法实现多态性。
我在python中有一个抽象class,想调用其中的非抽象方法。可以吗?
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()
未定义。
不知道为什么。
感谢任何帮助。
通常,所有方法都有一个名称空间,即 class 或它们所附加的对象。如果你有一个 class 的实例浮动(例如 self
,大部分时间),你可以调用该实例上的方法,自动将实例本身作为第一个参数传递 - 实例充当实例方法的命名空间。
如果您使用的是 class 方法或静态方法,那么命名空间几乎总是它们所附加的 class。如果您没有指定名称空间,那么 python 会假设您尝试调用的任何函数都在全局名称空间中,如果不是,那么您会得到一个 NameError
.
在这种情况下,以下内容应该适合您:
class MyAbstract(ABC):
def get_current():
print("current")
def get_state():
MyAbstract.get_current()
@abstractmethod
def get_time():
pass
你可以想象你有一个小的不可见的 @staticmethod
装饰器挂在 get_current()
上面标记它。这样做的问题是,现在您无法更改子 class 中 get_current()
的行为来影响 get_state()
中的更改。解决方案是使 get_state()
成为 class 方法:
@classmethod
def get_state(cls):
cls.get_current()
调用静态方法使用与调用 class 方法相同的语法(在这两种情况下您都可以使用 MyAbstract.get_state()
,但后者通过 class 您'将其作为第一个参数调用 。然后您可以使用此 class 作为名称空间来查找方法 get_current()
用于任何子 class 最近定义的方法,这就是您如何使用静态方法实现多态性。