gpt4 book ai didi

python - 调用 python3 的同级方法?

转载 作者:行者123 更新时间:2023-12-01 04:21:48 31 4
gpt4 key购买 nike

为了节省代码,我想在 python 3 中调用同一类中的另一个方法。不幸的是,我只能得到一个使用具有固定名称的对象的解决方案。我的测试代码应该是 self 解释的:

import os, sys

class Window():
konst = "2 ENTERED SECONDMETHOD"

def firstMethod(self):
print("1 ENTERED FIRSTMETHOD")

#Works
#But this is not universal
windowobj.secondMethod()

#Possible solutions that did not work

#secondMethod()
#NameError: name 'secondMethod' is not defined

#__class__.secondMethod()
#TypeError: secondMethod() missing 1 required positional argument:
#'self'

#self.secondMethod()
#NameError: name 'self' is not defined

#self.__class__.secondMethod()
#TypeError: secondMethod() missing 1 required positional argument:
#'self'

#super().secondMethod()
#AttributeError: 'super' object has no attribute 'secondMethod'

def secondMethod(self):
print(self.konst)

#Create Object
windowobj = Window()

windowobj.firstMethod()

最佳答案

调用self.secondMethod()是正确的方法。

def firstMethod(self):
print("1 ENTERED FIRSTMETHOD")
self.secondMethod()

证据如下:Ideone online compiler

下次请不要发布带有德语注释的代码。

关于python - 调用 python3 的同级方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33593389/

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