0

Trying to create a very simple Python class but confused by the use of 'self' in the constructor.

In the following constructor code snippet do 'r1' 'r2' 'server' ALL have to be prefaced with 'self.'? Ditto for the handler method 'user_callback'?

class App:
    def __init__(self,ip,port):
        self._ip=ip
        self._port=port
        r1 = pf.Relay(0)
        r2 = pf.Relay(1)
        server = OSCServer( ( self._ip, self._port) )
        server.addMsgHandler( "/1/push1", user_callback )
user2005121
  • 437
  • 1
  • 6
  • 16
  • If you want `r1`, etc to belong to that instance of `App`, yes. – azz Nov 05 '13 at 15:53
  • With `self.`, you access the members of the `App` instance. Without `self.`, you access global variables. See e. g. [this article](http://concentricsky.com/blog/2013/apr/pythons-magical-self) for more explanations. – Robin Krahl Nov 05 '13 at 15:53
  • @RobinKrahl with self., you access the members of INSTANCES OF the App class. Not the App class (object) itself. – jbat100 Nov 05 '13 at 15:57
  • Your life will be easier if you try things out for yourself. The code you post has no identifiable problem. – Marcin Nov 05 '13 at 15:58
  • @jbat100 yes, that’s what I wanted to write. ^^ Thanks, I changed it. – Robin Krahl Nov 05 '13 at 15:58

1 Answers1

1

Every instance method of a class in python is passed its instance as first parameter implicitly. That's why you need to add self as first argument for every instance method, otherwise you'll get an error.

Said this, what you do with self is the completely up to you. By doing self.x = 1 you're adding a new variable to the instance and just for that instance. If you intend to store, r1, r2, server variables for later usage in other methods then yes, you want to store them as instance variables. Otherwise you don't need to prefix them with self.

Classes in python behave like (and indeed have a) dictionary for managing its instances variables and methods. You add instance variables to their instances by doing self.x = 1.

Hope this helps!

Paulo Bu
  • 29,294
  • 6
  • 74
  • 73