Home > database >  How can I append an item from a class method to a list inside another class?
How can I append an item from a class method to a list inside another class?

Time:04-05

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

CodePudding user response:

Theres lots of things wrong with your question so I've bullet pointed them and then updated your snippet.

  • your instance of C is called a which is confusing
  • You pass in tolerance to your C initializer and never use it,
  • lst is a class variable of A but you aren't using it, instead you're making a new variable of the same name in your getAnswer function
  • getAnswer is never called.
  • getAnswer never "gets" anything so the function name is a bit misleading (havent modified)
  • you initiate B with two variables p1,p2 which don't exist in the scope of the function, but already exist in your pt list
class A:
  lst = []

class B:
  *#I implemented distance formula here*

class C: 
  def __init__(self, pt):
    self.pt = pt
    self.tolerance = None

  def getAnswer(self, tolerance):
    self.tolerance = tolerance

    d = B(self.pt[0],self.pt[1]).dist
    if d <= self.tolerance:
       A.lst.append(p2)

p_list = [p1, p2]
c = C(p_list)
c.getAnswer(7)
A.lst

Whilst 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.

CodePudding user response:

It does not work, because lst is a local variable inside the class/function. I would do:

class A:
    global lst
    lst = []
class C:
    #init
    def getAnswer(self, tolerance):
        #stuff
        #if
            lst.append(p2)

Here is a test:

>>> class A:
    global lst
    lst = []

>>> class C:
    def __init__(self):
        lst.append("This is appended to the list!")

>>> C()
<__main__.C object at 0x0000021D25CF5640>
>>> """I just called the C __init__ function, let's see if it worked"""
"I just called the C __init__ function, let's see if it worked"
>>> print(lst)
['This is appended to the list!']
>>> """Yay!"""
'Yay!'
>>> 
  • Related