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.

7 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.

13 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.

3 Likes

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.

4 Likes

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
1 Like

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.

7 Likes

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?

2 Likes

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.

4 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)
1 Like

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.

6 Likes
class Area:
 pi = 3.14
 def circle(radius):
  return pi*radius**2
area = Area.circle(5)

it returns pi is not defined.
How does a method works, doesn’t it uses the value of ‘pi’ which i have declared above the ‘circle method’.
if not then what does it mean by global namespace

Because when we write, pi the interpreter is looking for the variable in global scope. We need to scope it to our class.

self.pi

The global namespace is the top of all scopes where much of our code resides, and some, perhaps, global variables that will apply across all parts of the program.


Edit: missing ‘we’. November 20, 2020

4 Likes

I don’t think I understand the error properly: TypeError: washing_brushes() takes 0 positional arguments but 1 was given .

How does it mean that it takes 0 positional arguments but 1 was given, however, “self” wasn’t even passed in the method washing_brushes()?

Did you include self in your method parameter?

The issue with not including self (or any alternative name you have decided to use instead of it) is that, when you call an object’s method in Python, Python automatically plugs that object itself as an argument on the first position of the method.

That is to say that, while you are writing

abc.washing_brushes()

After you run the code, Python is essentially taking that command and interpreting it as:

abc.washing_brushes(abc)

The instance that is having its method called is always passed as an argument, even though you didn’t specify it to do so. So, if you don’t have a self or this or whatever argument waiting to receive that object in the method, Python will stumble and fail to make sense of what is happening: “the method requires no arguments, but one was received anyways, the ■■■■ is going on?”

1 Like