如果重命名 class,则维护静态方法调用
Maintaining staticmethod calls if class is renamed
我有一个 class,其中包含一个被其他方法多次调用的静态方法。例如:
class A:
def __init__(self):
return
@staticmethod
def one():
return 1
def two(self):
return 2 * A.one()
def three(self):
return 3 * A.one()
方法 one
是属于 class 的效用函数,但在逻辑上不是 class 或 class 实例的属性。
如果 class 的名称从 A
更改为 B
,我是否必须显式更改对方法 one
的每次调用从 A.one()
到 B.one()
?有更好的方法吗?
我曾经思考过这个问题,虽然我同意使用重构实用程序可能是最好的方法,但据我所知,在技术上可以通过两种方式实现此行为:
- 声明方法 a
classmethod
。
使用 __class__
属性。 导致代码相当混乱,并且由于我不知道的原因(?)可能被认为是不安全或低效的。
class A:
def __init__(self):
return
@staticmethod
def one():
return 1
@classmethod
def two(cls):
return 2 * cls.one()
def three(self):
return 3 * self.__class__.one()
a = A()
print(a.two())
print(a.three())
我有一个 class,其中包含一个被其他方法多次调用的静态方法。例如:
class A:
def __init__(self):
return
@staticmethod
def one():
return 1
def two(self):
return 2 * A.one()
def three(self):
return 3 * A.one()
方法 one
是属于 class 的效用函数,但在逻辑上不是 class 或 class 实例的属性。
如果 class 的名称从 A
更改为 B
,我是否必须显式更改对方法 one
的每次调用从 A.one()
到 B.one()
?有更好的方法吗?
我曾经思考过这个问题,虽然我同意使用重构实用程序可能是最好的方法,但据我所知,在技术上可以通过两种方式实现此行为:
- 声明方法 a
classmethod
。 使用
__class__
属性。 导致代码相当混乱,并且由于我不知道的原因(?)可能被认为是不安全或低效的。class A: def __init__(self): return @staticmethod def one(): return 1 @classmethod def two(cls): return 2 * cls.one() def three(self): return 3 * self.__class__.one() a = A() print(a.two()) print(a.three())