0

I have a class say:

class MyClass:
    def mymethod(self, data1, data2):
        print (self.data1)
        print (self.data2)

and I am calling this class somewhere in a Django view and sending this argument like:

mycls = MyClass()
mycls.mymethod(data1, data2)

When I do this it says 'MyClass' object has no attribute 'data1'

What's wrong?

3 Answers 3

2

Because you haven't assigned to them yet. I'm guessing that what you're trying to do is something like this:

class MyClass:
    def mymethod(self, data1, data2):
        self.data1 = data1
        self.data2 = data2
        print(self.data1)
        print(self.data2)

Until you actually assign to self.something (even if you have a parameter to the method called something), that variable doesn't exist. something and self.something are two different things.

Or, if you're just trying to print the values of two parameters to a method, you might want to do this instead:

class MyClass:
    def mymethod(self, data1, data2):
        print(data1)
        print(data2)
Sign up to request clarification or add additional context in comments.

Comments

0

in MyClass.mymethod you totally ignore the data1 and data2 args and try to print the (obviously non-existant) instance attributes self.data1 and self.data2. Either it's a typo (yeah, it happens ) or you don't understand what is self in this context and the difference between arguments and attributes...

Comments

0

try this data1 you are sending and in mymethod are different :

class MyClass:
    def mymethod(self, data1, data2):
        self.data1 = data1
        self.data2 = data2
        print self.data1
        print self.data2

OR

         print data1
         print data2

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.