newprint
newprint

Reputation: 7136

Getting AttributeError after invoking class function in Python

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 !

Upvotes: 0

Views: 1606

Answers (3)

Dharmesh Patel
Dharmesh Patel

Reputation: 81

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()

Upvotes: 0

Mike Axiak
Mike Axiak

Reputation: 11994

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 :)

Upvotes: 3

John Kugelman
John Kugelman

Reputation: 361595

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

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

Upvotes: 1

Related Questions