如何在基础 class 中使用重载的静态方法?
How to use overloaded static method in a base class?
我想在 _get_all_odd()
中使用 _get_all()
的重载版本,有办法吗?
将其作为 BaseClass._get_all()
调用会引发异常 "Must be overloaded"
,
调用它 _get_all()
会产生 not recognised
错误。
########################################################################
class BaseClass:
@staticmethod
def _get_all():
raise Exception("Must be overloaded")
@staticmethod
def _get_all_odd():
result = [sh for sh in BaseClass._get_all() if sh%2 == 1]
return result
##################################################################
class Shape(BaseClass):
__all_shapes = [1, 2, 3]
@staticmethod
def _get_all():
return Shape.__all_shapes
print(Shape._get_all_odd())
是否有必须使用静态方法的原因?使用 classmethods 在功能上是相同的,但是 classmethods 更了解 class 结构。
例如,稍作改动即可:
class BaseClass:
@classmethod
def _get_all(cls):
raise Exception("Must be overloaded")
@classmethod
def _get_all_odd(cls):
result = [sh for sh in cls._get_all() if sh%2 == 1]
return result
class Shape(BaseClass):
__all_shapes = [1, 2, 3]
@classmethod
def _get_all(cls):
return Shape.__all_shapes
print(Shape._get_all_odd())
我想在 _get_all_odd()
中使用 _get_all()
的重载版本,有办法吗?
将其作为 BaseClass._get_all()
调用会引发异常 "Must be overloaded"
,
调用它 _get_all()
会产生 not recognised
错误。
########################################################################
class BaseClass:
@staticmethod
def _get_all():
raise Exception("Must be overloaded")
@staticmethod
def _get_all_odd():
result = [sh for sh in BaseClass._get_all() if sh%2 == 1]
return result
##################################################################
class Shape(BaseClass):
__all_shapes = [1, 2, 3]
@staticmethod
def _get_all():
return Shape.__all_shapes
print(Shape._get_all_odd())
是否有必须使用静态方法的原因?使用 classmethods 在功能上是相同的,但是 classmethods 更了解 class 结构。
例如,稍作改动即可:
class BaseClass:
@classmethod
def _get_all(cls):
raise Exception("Must be overloaded")
@classmethod
def _get_all_odd(cls):
result = [sh for sh in cls._get_all() if sh%2 == 1]
return result
class Shape(BaseClass):
__all_shapes = [1, 2, 3]
@classmethod
def _get_all(cls):
return Shape.__all_shapes
print(Shape._get_all_odd())