gpt4 book ai didi

python - 在其方法之外引用一个类?

转载 作者:太空宇宙 更新时间:2023-11-03 16:43:20 25 4
gpt4 key购买 nike

我需要在我的程序中提供类似的东西

class the_class_name(Parent):
the_attribute = self.parent_class_method()
#the parent class method will return a value
#but I cannot use self here since there's no self

我该如何执行此操作?还有其他替代方案可以帮我完成这项工作吗?

我尝试过像这样使用__init__:

def __init__(self):
Parent.__init__(self)
self.attribute = self.the_method()

但是我在创建对象时遇到了问题,它不会再接收 Parent 类通常接收的任何参数

最佳答案

听起来您正在寻找 __init__:

class TheClassName(Parent):
def __init__(self):
# Set attribute to the result of the parent method
self.attribute = super(TheClassName, self).the_method()

编辑

如果您的父类在其自己的 __init__ 函数中具有参数,请将它们包含在子类中:

class Parent(object):
def __init__(self, foo, bar):
...

@classmethod
def the_method(cls):
...


class TheClassName(Parent):
def __init__(self, foo, bar):
super(TheClassName, self).__init__(foo, bar)
self.attribute = super(TheClassName, self).the_method()

我不太明白为什么当您需要值时不直接调用子对象的父方法。

关于python - 在其方法之外引用一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36578813/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com