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?

vitaliis
4,1975 gold badges26 silver badges48 bronze badges
asked Jul 1, 2015 at 11:50

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)
answered Jul 1, 2015 at 11:51
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...

answered Jul 1, 2015 at 11:53

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
answered Jul 1, 2015 at 11:55

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.