新学Python:遇到新的属性

2024-05-03 18:14:43 发布

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

类newnode:

def _init_(self):
    self.x=1
def nextmethod(self,value):
    self.result=value+self.x
    print(self.result)

def main():

node1=newnode()
node1.nextmethod(6)

如果name='main':

main()

C:/Users/hp/Desktop/untitled0.py", line 5, in nextmethod self.result=value+self.x

AttributeError: 'newnode' object has no attribute 'x'


Tags: nameselfinitvaluemaindefresultusers
1条回答
网友
1楼 · 发布于 2024-05-03 18:14:43

只需使用以下代码:

class newnode:
    def __init__(self):
        self.x=1
    def nextmethod(self,value):
        self.result=value+self.x
        print(self.result)

def main():
    node1=newnode()
    node1.nextmethod(6)

if __name__=='__main__':
    main()

记住init有双下划线

相关问题 更多 >