#1
  1. Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2002
    Posts
    14
    Rep Power
    0

    Declaring Python class variables


    Playing around with Python for the first time and have a question about classes - how to you declare class variables? I know you don't have to but I'd like to to make the class easier to read.

    In PHP, for example, I might do this;

    Code:
    class Test {
        var $message; // declare variable
        function Test ($message) {
            $this->message=$message;
        }
    
        function get() {
            return $this->message;
        }
    }
    In Python I've got as far as;

    Code:
    class Test:
        def __init__(self,message):
            self.message=message
    
        def get(self):
            return self.message
    I'd like to be able to declare the message variable to make it readable.

    One other question; when declaring class methods, do I always have to make the first parameter "self"? And why is it Python does this in the first place? Seems a little odd compared to methods in Java or PHP for example.

    Many thanks.
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2002
    Posts
    32
    Rep Power
    13
    >> how to you declare class variables?

    You mean instance variables (data members)? Like this:
    Code:
    class Test:
        my_attr = '';
        def __init__(self,message):
            self.message=message
    
        def get(self):
            return self.message
    Or you can just use self.message like you showed and the instance variable will spring into existence.

    To define private variables, add 2 leading underscores (e.g. __myvar) and Python will mangle it into _classname__myvar. Data hiding in this case is not strictly enforced as in Java (since you can access it using '_classname__myvar' - it's more of a 'contractual agreement' basis)

    >> when declaring class methods, do I always have to make the first parameter "self"? And why is it Python does this in the first place?

    Consider an object x of class Test (which you defined above). Typically, from outside the class, you'd call the get() method of x like so:
    Code:
    msg = x.get();
    What Python does is translate it into
    Code:
    msg = Test.get(x);
    Why the parameter is called 'self' is a matter of convention (meaning you can use something like 'pinkgoblin' instead of 'self', but it's good to follow the convention to prevent confusing others)
  4. #3
  5. Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2002
    Posts
    14
    Rep Power
    0
    Many thanks. Clears up alot.

IMN logo majestic logo threadwatch logo seochat tools logo