Reputation: 5863
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?
Upvotes: 0
Views: 167
Reputation: 1402
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
Upvotes: 0
Reputation: 77932
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...
Upvotes: 0
Reputation: 13354
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)
Upvotes: 2