[英]How to call class method within namespace of the same class in python 3.x
When working with python instances, it is possible to access bound methods of the same class using self
.使用 python 实例时,可以使用
self
访问相同 class 的绑定方法。 This resolves to a method corresponding to the same class in hierarchy.这解析为与层次结构中相同的 class 对应的方法。
class A:
def f(self):
return 1
def __init__(self):
self.v = self.f()
class B(A):
def f(self):
return 2
b = B()
# b.v is set to 2
But, when working with class methods, there is no apparent way of accessing methods of the same class as above.但是,当使用 class 方法时,没有明显的方法可以访问与上述相同的 class 方法。
In my use case, f
above needs to be a class method and I need to set class variable v
according to f
corresponding to the same class.在我的用例中,上面的
f
需要是 class 方法,我需要根据对应于相同 class 的f
设置 class 变量v
。 Somewhat like:有点像:
class A:
@classmethod
def f(cls):
return 1
v = resolution_of_calling_class.f()
class B(A):
@classmethod
def f(cls):
return 2
# B.v should be 2
edit : v
is actually an attribute defined by parent class, which should find a method overridden by child class编辑:
v
实际上是由父 class 定义的属性,它应该找到由子 class 覆盖的方法
You just need to override __new__
method, since it is invoked before the __init__
and its purpose is to create an instance, that will be initialized by __init__
.您只需要覆盖
__new__
方法,因为它在__init__
之前调用,其目的是创建一个实例,该实例将由__init__
初始化。
class A:
def __new__(cls, *args, **kwargs):
cls.v = cls.f()
return super().__new__(cls, *args, **kwargs)
@classmethod
def f(cls):
return 1
class B(A):
@classmethod
def f(cls):
return 2
a = A()
print(a.v)
b = B()
print(b.v)
1
2
I am not 100% sure I understand what you are trying to do.我不是 100% 确定我理解你想要做什么。
I used your code above and我在上面使用了您的代码
class A:
@classmethod
def f(cls):
return 1
class B:
@classmethod
def f(cls):
return 2
print(B.f())
gives me 2 just as I expected it would.正如我预期的那样给我 2。 Should B be a child class of A as in the first example?
B 应该是 A 的子 class 吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.