0

Very simple class(source below) written in Python.

After constructing obj1 = myClass(12) and calling class function obj1.printInfo(), I am getting an error - AttributeError: type object 'myClass' has no attribute 'arg1' What might be the source of the problem ??

class myClass(object):
 def __init__(self, arg1, arg2 = 0):
 self.arg1 = arg1
 self.arg2 = arg2
 def printInfo (self):
 print myClass.arg1, myClass.arg2
obj1 = myClass(12)
obj1.printInfo()

Thanks !

asked Dec 7, 2010 at 2:40

3 Answers 3

3

You want to use replace the body of printInfo(self) with:

def printInfo(self):
 print self.arg1, self.arg2

The use of self here is not to specify the scope, as it is sometimes used in Java (MyClass.this) or in PHP. In this function, self is actcually the object that contains arg1 and arg2. Python is very explicit in this manner. In your previous method, you assigned arg1 and arg2 for self, so you should expect to get arg1 and arg2 back off of self.

With regard to your second question, if you want a "class" function (i.e. a static method), then you still need a reference to your obj1 to access its properties. For example:

class MyClass(object):
 def __init__(self, arg1, arg2 = 0):
 self.arg1 = arg1
 self.arg2 = arg2
 @staticmethod
 def printInfo(obj):
 print obj.arg1, obj.arg2
obj1 = MyClass(12)
MyClass.printInfo(obj1)

Also be sure to read PEP8 when you get a chance :)

answered Dec 7, 2010 at 2:43
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for an Answer. I will extend this question a little, what if I have some non-class function f1() that will be called by printInfo() and f1() would use obj1 arguments. Would this be possible at all ? Thanks !
Edited answer to reflect your comment.
1

Brain fart, eh? Switch myClass.arg1 to self.arg1:

def printInfo (self):
 print self.arg1, self.arg2
answered Dec 7, 2010 at 2:43

Comments

0

You can do it like this:

def f1(arg1, arg2):
 print arg1, arg2
class myClass(object):
 def __init__(self, arg1, arg2 = 0):
 self.arg1 = arg1
 self.arg2 = arg2
 def printInfo (self):
 f1(self.arg1, self.arg2)
obj1 = myClass(12)
obj1.printInfo()
Svante
51.8k11 gold badges84 silver badges127 bronze badges
answered Dec 7, 2010 at 12:27

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.