Does the first parameter to a class method have to be named self?

Question

Does the first parameter to a class method always need to be named self?

Answer

self is not a reserved or special keyword in Python. It is, however, a strongly encouraged practice to always name the variable referencing the current object as self. This will make your code easier to understand by other people as it will follow the common naming convention.

8 Likes
>>> class foo(object):
	def __init__(this, name, age):
		this.name = name
		this.age = age

		
>>> bar = foo("Bar", 63)
>>> bar
<__main__.foo object at 0x00F0FC10>
>>> bar.name
'Bar'
>>> bar.age
63
>>> 

Why would we opt for bucking the recommended diction? The syntax highlighting is very supportive of this, no pun intended, supportive of self is more the point.

8 Likes

3 posts were merged into an existing topic: FAQ: Learn Python: Classes - Methods with Arguments

Sure seems so… look at the following code from here: https://www.codecademy.com/courses/learn-python-3/lessons/data-types/exercises/methods

class Rules:
  def washing_brushes(self):
    print("Point bristles towards the basin while washing your brushes.")

abc = Rules()

abc.washing_brushes()

#Output: Point bristles towards the basin while washing your brushes.

If i write def washing_brushes(): instead, i get this error: TypeError: washing_brushes() takes 0 positional arguments but 1 was given.

So it seems mentioning self is compulsory when defining a custom method inside your custom class.

1 Like

Is self in python same idea how we use this in JS ?

Yes, very much the same. They both are internal variables that reference the execution context of the current instance.

1 Like

even though I don’t call class only defining it python won’t let me use variables other then arguments passed directly in method without using self :

class Circle:
  pi = 3.14
  def area(self, radius):
    return pi * radius ** 2

I’m not trying to access area method why still python throw error pi is not defined . Is it related to variable scope ? if yes self word is rescue for solving variable scope ? but it looks like pi in Circle class is visible to area method as it is defined in outer layer like how global variables are defined . this word was always secret to me .

either of these works also: which encourage me to think it is must be related to variable scope but can’t figure out why method inside class can’t have access to variable defined inside class like how global variables are accessible in functions defined in certain .py file

Circle().pi
circle.pi

Because Python is looking for and expecting pi to be an attribute of the class.

self.pi

When it looks for pi it expects to find it in global scope.

Say, for instance we import the math constant

from math import pi as PI

Now your class can reach out for the global

return PI * radius ** 2

Of course then we run the risk that PI could get changed or deleted.

1 Like

So a function definition, wherever it takes place, only has access to global variables and variables local to the definition and that’s it, right?

The definition doesn’t have access to variables defined inside the class, even if the function definition takes place inside that class. Or is it that variables defined inside the scope of a class aren’t really variables, but they’re class attributes, which are not accessible anywhere except through that class?

If we define a function as globally accessible anywhere in the namespace in which it is defined then it is classless. It can be called from anywhere in that namespace and is not associated with any particular object.

A method, on the other hand is defined in the context of a class, so can only be accessed by the class itself, or by instances of that class.

Likewise, variables are globally accessible anywhere in the namespace in which they are defined. Think of function body as being a protected namespace, but it can still have functions of its own, internally along with its local variables which are global from the perspective of those functions.

Attributes are associated with a class and only the class itself (as in class attributes), or instances of that class (as in instance attributes) can access them. An instance can also access class attributes on its self object.

2 Likes

Right. I think the confusing part is that it seemed at first there’s a kind of hierarchy of scopes, in which the inner scopes are not accessible by the outer, but the outer are accessible by the inner.

variable1 #(can be accessed anywhere in the program)
    for loop
        variable1
        variable2 #(can only be accessed in this loop)
    function
        variable1
        variable3 #(can only be accessed in this function)
        for loop
            variable1
            variable3
            variable4 #(can only be accessed in this loop)

However, for classes, it seems this is not the case.

Class
    variable1 #(can be accessed anywhere in the program, as part of the class,
    #but not by itself. a class can be thought of as similar to an imported module,
    #maybe? as in, a separate namespace)

    function
        variable1 #(doesn't work)
        Class.variable1 #(works)
    for loop
        variable1 #(probably doesn't work, haven't tested)

variable1 #(doesn't work)
Class.variable1 #(works)

Correct. Scope is nothing more than the namespace environment where a function or variable are defined. Classes differ slightly because their instances have context that lets them reach back into the class definition for attributes and methods, even though they are outside of that namespace. Their membership in the class is what grants them access.

2 Likes