Python:从方法访问定义的变量

2024-06-01 00:04:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有不起作用的代码,我不太清楚为什么。这是我的密码:

pal1= timingPage(createSelenium.sel)
pal1.gpsTimingMode.setOption()

同时,这里是timingpage类:

class timingPage:

    def __init__(self,sel):
        self.gpsTimingMode = option(self.selObject)
        self.gpsTimingMode.id="hi"

在选项类中:

class option:
    def setOption(self):
        print str(self.id)

引发此错误:

AttributeError: option instance has no attribute 'id'


class option:

def __init__(self,sel):
    self.selObject=sel
def setOption(self):
    print str(self.id)
    print "selOption called"
    # this method is a general method for selecting a option, so that the caller does not need to know the type or structure
    for pre in self.prereq:
        print "Prerequisite"+str(pre)+"called"

有没有办法解决这个问题

谢谢


Tags: selfidinitdefclassoptionprintstr
2条回答

如果你不在任何地方定义self.id,你就不能调用它

要解决这个问题,请考虑在__init__中定义它

如果不在任何地方定义object.id,则无法访问它

有关如何定义属性,请参见Python documentation

相关问题 更多 >