如何将项目从类方法附加到另一类的列表?
我想将项目附加到类A类
中的列表中,但是当我在过程之后调用列表时,它只会返回一个空列表。我如何成功地附加物品?
这就是我尝试的。我在getanswer
方法内实现lst.append
,但附加不成功。请注意,我仅包括我的代码段,因为那里还有其他事情。我只是关心知道如何成功地申请附加功能。
class A:
lst = []
class B:
*#I implemented distance formula here*
class C:
def __init__(self, pt, tolerance):
self.pt = pt
def getAnswer(self, tolerance):
self.tolerance = tolerance
d = B(p1,p2).dist
if d <= self.tolerance:
lst.append(p2)
p_list = [p1, p2]
a = C(p_list, 7)
A.lst
I want to append an item to the list in Class A
but when I call the list after the process, it just return an empty list. How exactly can I successfully append an item?
This is what I tried. I implement lst.append
inside the getAnswer
method but the appending was unsuccessful. Note that I only included snippet of my code because there are other things going on there. I am just concerned on knowing how can I successfully to the appending function.
class A:
lst = []
class B:
*#I implemented distance formula here*
class C:
def __init__(self, pt, tolerance):
self.pt = pt
def getAnswer(self, tolerance):
self.tolerance = tolerance
d = B(p1,p2).dist
if d <= self.tolerance:
lst.append(p2)
p_list = [p1, p2]
a = C(p_list, 7)
A.lst
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的问题有很多问题,所以我已经指出了它们,然后更新了您的片段。
c
的实例被称为a
,这使c
initializer的容忍感到困惑,并且永远不会使用它,lst
lst 是a
的类变量,但您没有使用它,而是在getanswer
functiongetanswer
从不“获取”任何东西,因此函数名称有点具有误导性(修改了),p1,p2
在范围内不存在的b该函数,但在 您的
pt
列表中已经存在有有效的用例,可变名称太模糊了,否则建议。Theres lots of things wrong with your question so I've bullet pointed them and then updated your snippet.
C
is calleda
which is confusingC
initializer and never use it,lst
is a class variable ofA
but you aren't using it, instead you're making a new variable of the same name in yourgetAnswer
functiongetAnswer
is never called.getAnswer
never "gets" anything so the function name is a bit misleading (havent modified)p1,p2
which don't exist in the scope of the function, but already exist in yourpt
listWhilst the above will update your list, its still odd to have
C
change A's list, I've left it as is because there are valid use cases and the variable names are too vague too suggest otherwise.它不起作用,因为 lst 是类/函数内的局部变量。我会这样做:
这是一个测试:
It does not work, because lst is a local variable inside the class/function. I would do:
Here is a test: