Samama Fahim
Samama Fahim

Reputation: 113

Why Dot Notation For "Method" Variables and Not For Others?

Let's say I create the following class in Python:

class SomeClass(object):
    variable_1 = "Something"
    def __init__(self, variable_2):
        self.variable_2 = variable_2 + self.variable_1

I do not understand why variables lying outside the method (should I say function?) definition, but inside the body of class, are not named using the dot notation like variable_1, and variables inside the method definition are named - for example: self.variable_2 - or referenced - for example: self.variable_1 using the dot notation. Is this just a notation specific to Python or is this for some other reason?

Upvotes: 0

Views: 120

Answers (1)

Sylvain Biehler
Sylvain Biehler

Reputation: 1433

It is not something you will find in C++ or java. It is not only a notation. See the documentation documentation:

classes partake of the dynamic nature of Python: they are created at runtime, and can be modified further after creation.

And it is the same for functions.

Here is a valid way to define a class:

def f1(self, x, y):
    return min(x, x+y)

class C:
    text = 'hello world'
    f = f1
    def g(self):
        return self.text
    h = g

f, gand hare attributes of C. To make it work, it is important to pass the object as an argument of the functions. By convention, it is named self.

This is very powerful. It allows to really use a function as an attribute. For example:

c = C()
class B:
    text = 'hello word 2'
    g = c.g

The call to B.g() will return 'hello word 2'. It is only possible because of the use of self.

For the record, you may also read the documentation of global and of the variable scope in general.

Upvotes: 1

Related Questions