I want badges
I want badges

Reputation: 6505

Call a function inside a class when calling the class in python

This simple example is what I dont get to work or understand in my more complex script:

class printclass():
    string="yes"
    def dotheprint(self):
        print self.string
    dotheprint(self)
printclass()

When the class is called, I expected it to run the function, but instead it will tell me that "self is not defined". Im aware this happens on the line:

dotheprint(self)

But I dont understand why. What should I change for the class to run the function with the data it already has within? (string)

Upvotes: 0

Views: 1493

Answers (2)

lucasg
lucasg

Reputation: 11002

You really need to understand Object-Oriented Programming and its implementation in Python. You cannot "call" a class like any function. You have to create an instance, which has a lifetime and methods linked to it:

o = printclass() # new object printclass
o.dotheprint()   # 

A better implementation of your class:

class printclass():
    string="yes"         #beware, this is instance-independant (except if modified later on)

    def dotheprint(self):
        print self.string

    def __init__(self):  # it's an initializer, a method called right after the constructor
         self.dotheprint()

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121196

You misunderstand how classes work. You put your call inside the class definition body; there is no instance at that time, there is no self.

Call the method on the instance:

instance = printclass()
instance.dotheprint()

Now the dotheprint() method is bound, there is an instance for self to refer to.

If you need dotheprint() to be called when you create an instance, give the class an __init__ method. This method (the initializer) is called whenever you create an instance:

class printclass():
    string="yes"

    def __init__(self):
        self.dotheprint()

    def dotheprint(self):
        print self.string

printclass()

Upvotes: 3

Related Questions