0

I have one class. For that i want to append data to constructor empty list variable. I am trying to append data. But it's not working and throwing error as "NameError: name 'items' is not defined". before this code has been worked.

Here it my code snippet :

class data:
    def __init__(self,items=[]):
        self.items = items
        self.m1(n)
    def m1(self,n):
        self.n=2
        for i in range(self.n):
            d = input('enter the values :')
            self.items.append(d)
        print(self.items)
d=data(items)

2 Answers 2

2

here are some issues wrong:

1.) On line 11, items is not defined anywhere before trying to initialize the class, so you end up receiving an error when you call

 d=data(items)

2.) On line 4, n is not defined. It is neither passed in along as a parameter with the constructor or defined elsewhere within the constructor block. You will need to define n.

Here is a working version though, with all the variables properly defined:

class data:
    def __init__(self, n, items=[]):
        self.items = items
        self.m1(n)

    def m1(self, n):
        self.n=2
        for i in range(self.n):
            d = input('enter the values :')
            self.items.append(d)
        print(self.items)

items = [1, 5, 7]
d = data(2, items)
Sign up to request clarification or add additional context in comments.

4 Comments

same error it showing. previously my code has been worked. but now it's not working.
can you try again. I made some edits. The main issue is you need to already define items somewhere already before initializing d items = [1, 5, 7] d = data(2, items)
ok...thanks. it's working. but previously my code snippet is working. now it's not working. what's the issue for that code snippet.
the same things I highlighted in the answer above. On line 11, items is not defined anywhere, in the constructor, n is not defined anywhere either.
0
class data:
def __init__(self,number,name,list_values=[]):
    self.number = int(input('Enter a number :'))
    self.name = name
    self.list_values = list_values
    self.m1()
def m1(self):
    for i in range(self.number):
        items = input('Enter the values :')
        self.list_values.append(items)
    print(self.list_values)
list_values= None
d=data('siddarth',list_values)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.