Python中文
首页
教程
问答
标签
搜索
登录
注册
AttributeError调用class1中的class2时,class1没有\uuu init \uuuuu attribu
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>我是OOP新手,正在尝试使用两个类。我正在尝试将一个直到<code>Class1</code>运行到<code>Class2</code>时才创建的属性馈送到<code>Class1</code>,但是当我运行<code>Class1</code>时得到了一个AttributeError</p> <pre><code>class Class1(): #some code.... def function1(): x=5 number=2 test=class2(x) answer=Class2.function2(Class2,number) print(answer) class Class2(): def __init__(self, y): self.y=y def function2(self, z): calculated_answer=self.y+z return calculated_answer #several more functions that also use y </code></pre> <p>我试图避免在<code>Class2</code>中的每个新函数中重复将<code>y</code>定义为<code>x</code>,所以我想我可以用<code>x</code>运行<code>Class2</code>,然后用<code>function2</code>和number来打印<code>7</code>。相反,我得到:<code>AttributeError: type object 'Class2' has no attribute 'y'</code></p> <p>起初我以为我误解了<code>__init__</code>,所以我运行了以下代码以确保:</p> <pre><code>class Class2(): def __init__(self, y): self.y=y def function2(self, z): calculated_answer=self.y+z return calculated_answer x=5 test=class2(x) </code></pre> <p>但当我在shell中键入<code>test.function2(2)</code>,并按预期返回<code>7</code>时,这种方法就可以正常工作</p> <p>我想我一定是误解了如何使用<code>Class2</code>,但我不知道我做错了什么</p> <p>如何在不在<code>Class2</code>中的每个函数中定义<code>x</code>的情况下消除此错误</p>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>很难理解您的代码,但一个明显的错误是在这一行</p> <pre><code> answer=Class2.function2(Class2,number) </code></pre> <p>把它改成</p> <pre><code> answer = test.function2(number) </code></pre> <p>通过使用必需的init参数调用对象来创建对象时,在调用类的函数时不需要传递self参数。它是自动传递的</p>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
我想从用户inpu创建一个类的实例
6 回答
我想从用户导入值,为此
9 回答
我想从用户那里得到一个整数输入,然后让for循环遍历该数字,然后调用一个函数多次
10 回答
我想从用户那里收到一个列表,并在其中执行一些步骤,然后在步骤完成后将其打印回来,但它没有按照我想要的方式工作
8 回答
我想从用户那里获取输入,并将值传递给(average=dict[x]/6),然后在那里获取resu
2 回答
我想从第一个列表中展示第一个词,然后从第二个列表中展示十个词,以此类推- Python
2 回答
我想从第一个空lin开始解析文本文件
6 回答
我想从简历、简历中提取特定部分
6 回答
我想从给定字典(python)的字符串中删除\u00a9、\u201d和类似的字符。
2 回答
我想从给定的网站Lin下载许多文件扩展名相同的Wget或Python文件
5 回答
我想从网上搜集一些关于抵押贷款的数据
3 回答
我想从网站上删除电子邮件地址
6 回答
我想从网站上读取数据该网站包含可下载的文件,然后我想用python脚本把它发送给oracle如何?
1 回答
我想从网站中提取数据,然后将其显示在我的网页上
10 回答
我想从网页上提取统计数据。
7 回答
我想从网页上解析首都城市,并在用户输入国家时在终端上打印它们
7 回答
我想从色彩图中删除前n个颜色,而不丢失原始颜色数
9 回答
我想从课堂上打印字典里的键
2 回答
我想从费用表中获取学生上次支付的费用,其中学生id=id
5 回答
我想从较低的顺序对多重列表进行排序,但我无法在一行中生成结果
3 回答