0

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)

2 Answers 2

3

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()
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

__init__ is not a constructor. It doesn't construct instances. It is an initializer; it is called after the item has been constructed already. __new__ is the constructor.
oh you're right. Since the aren't any memory management in Python, I hardly use new. I'll fix my answer.

Your Answer

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.