在Python中,如何从子类中调用从父类继承的类方法?你知道吗
最低限度的工作示例是:
class Parent:
my_member_variable = 348627
@classmethod
def class_method(cls):
print("I made it from {} and my_member_variable = {}.".format(
cls, cls.my_member_variable))
class Child(Parent):
my_member_variable = 982374982
cls.class_method() # DOES NOT WORK! I want to have the result I
# made it from <class '__main__.Child'> and
# my_member_variable = 982374982.>>.
不幸的是,这会产生错误NameError: name 'cls' is not defined
。你知道吗
我如何调用类方法class_method
,它是类Child
从类Parent
继承的,在类Child
内,同时使用类my_member_variable
,而不是从类Parent
继承的?你知道吗
可以使用super().class\u method()而不是cls.U类方法在儿童班里。你知道吗
您试图在类
Child
存在之前调用该方法。您的class
语句(方法调用暂时被注释掉)相当于
对
class
语句的主体进行求值,以确定传递给type
的第三个参数的内容。如果取消对方法调用的注释,很容易看到在type
返回名称cls
要引用的新类之前,cls.class_method
被求值。你知道吗换句话说,在上面的代码中,
cls
是未定义的。但很明显你不能简单地说因为
Child
也还没有定义,而您要分配给cls
的值是尚未发生的对type
的调用的返回值。你知道吗输出:
我想这就是你想做的。希望有帮助
相关问题 更多 >
编程相关推荐