Brian Fitzpatrick
Brian Fitzpatrick

Reputation: 2503

Is there a convention for using self while initializing a class in python?

I'm curious if there is a convention in python for using the self variable in the __init__ method of a class.

Consider the simple Person class.

class Person:

    def __init__(self, firstname, lastname):
        self.firstname = firstname
        self.lastname = lastname

        self.fullname = ' '.join([self.firstname, self.lastname])

The __init__ method stores the two inputs firstname and lastname as instance variables and then uses these instance variables to define the fullname instance variable.

It seems like the self variable is unnecessary when defining self.fullname, so Person could alternatively be written as:

class Person:

    def __init__(self, firstname, lastname):
        self.firstname = firstname
        self.lastname = lastname

        self.fullname = ' '.join([firstname, lastname])

Is there any meaningful difference between these two ways of writing the class? I don't see a difference other than the fact that the second option requires less horizontal space to define self.fullname, which might be desirable.

Upvotes: 1

Views: 103

Answers (1)

holdenweb
holdenweb

Reputation: 37003

The second example is a (very slightly) more efficient way to write the same code.

In general the methods of an instance use instance variables to maintain the instance's state. Since each method gets the same object as self, the different methods can communicate over time through their use.

In both examples firstname and lastname are so-called "local variables," whose lifetime is only that of the method in which they are bound. Because they can be looked up more quickly (for reasons we needn't go into) as well as easier to type they are usually preferred for values with a limited lifetime.

Upvotes: 1

Related Questions