nandita
nandita

Reputation: 1

Cannot access class variable in class method

class Bin():
a=[]
def g(self,e):
    self.a.append(e)
o=Bin()
o.g(3)
o.g(4)
o.g(5)
o.g(6)

Traceback (most recent call last):
  File "<string>", line 28, in <module>
File "<string>", line 9, in bs
NameError: name 'a' is not defined

how to deal with this error? i wanna append the list inside the class with given elements and use the list 'a' in other class methods too.

Upvotes: 0

Views: 74

Answers (1)

S.B
S.B

Reputation: 16486

Fix your indentation:

class Bin:
    a = []

    def g(self, e):
        self.a.append(e)


o = Bin()
o.g(3)
o.g(4)
o.g(5)
o.g(6)

print(Bin.a)

Output : [3, 4, 5, 6]

Upvotes: 1

Related Questions