Python not use self

SELF in Python

Every professional or student using Python will have to create an instance of a class anytime during his programming career. We use it using the self keyword. Programmers use it in method definition or initialization of variables. This article is about the self parameter along with what is self in Python? What does it do? How to use it and some other crucial topics related to SELF.

What is Self?

The self parameter is a reference to the instance of a class. It aids in accessing the variables which belong to a class. One can use any other name like mine or me instead of self. It should be the first parameter in the function of a class while defining the function.

Here are 2 example:

class chkr: def __init__(self): print("The address of self in this class is: ", id(self)) obj = chkr() print("The address of class object is: ", id(obj))
class Student: def __init__(myobj, name, age): myobj.name = name myobj.age = age def myfunc(abc): print("Hello my name is " + abc.name) p1 = Student("Joydeep", 25) p1.myfunc()

Here is another example of using the self parameter:

class sucar(): # init method or constructor def __init__(self, name, color): self.name = name self.color = color def show(self): print("The car's name is", self.name ) print("And, its color is", self.color ) # both the objects have a different self that contains their attributes Supra = sucar("Supra", "blue") Mercedes = sucar("Mercedes", "green") Supra.show() # same output as car.show(Supra) Mercedes.show() # same output as car.show(Mercedes)

Is the self a keyword?

Self acts as a keyword in other programming languages like C and C++. In Python, self is a parameter in a method definition. Professionals state that using self enhances the code readability. One can replace self with anything else as the first parameter of a method like mine, obj, etc.

Читайте также:  Java пустая строка как null

Follow the below example:

class myClass: def show(other): print(“other in place of self”)

Why self ought to be the first parameter of instance methods

Let’s take the help of an example:

class Rect (): def __init__(self, x = 0, y = 0): self.x = x self.y = y def ar (self): return (self.x * self.y) rec1=Rect(6,10) print ("The rectangle's area is:", rec1.ar())

In the above example, __init__ passed two arguments but defined three parameters, likewise the area().
Here, rect.ar and rec1.ar in the above code are different.

>>> type(Rectangle.area ) >>> type(rec1.area)

Here, Rectangle.area is a function, and rec1.area is a method. Python has a unique feature that allows passing an object as the first argument in any function.

Here, rec1.area() and Rectangle.area(rec1) are similar

Commonly, the related class function gets called by putting the method’s object before the first argument when the method gets called with some arguments.

That means obj.method(args) transforms to class.method(obj, args). That’s why self ought to be the first parameter of instance methods in Python.

What is the difference between self and __init__?

  • Self: It is the instance of a class. With the help of self, one can access all the methods and attributes of a Python class.
  • __init__: It is a reserved method of Python classes. It is a constructor in OOP concepts. Whenever an object gets created from a class, __init__ gets called. It enables the class to initialize class attributes.

The self parameter is a reference to the instance of a class. The reason Python programmers need to use self is that in Python we do not implement the @ syntax for referring to the instance attributes.

Accessing the instances through self is much faster and can smoothly work with the members associated with the class. It aids in accessing the variables which belong to a class. It can have other names instead of self.

It behaves as a keyword in programming languages except for Python. In Python, self is a convention that programmers follow, a parameter in a method definition.

  • Learn Python Programming
  • Addition of two numbers in Python
  • Null Object in Python
  • pip is not recognized
  • Python Comment
  • Python Continue Statement
  • Armstrong Number in Python
  • Python lowercase
  • Python String find
  • Top Online Python Compiler
  • Python String Concatenation
  • Python Print Without Newline
  • Id() function in Python
  • Reverse Words in a String Python
  • Ord Function in Python
  • Only Size-1 Arrays Can be Converted to Python Scalars
  • Area of Circle in Python
  • Attribute Error Python
  • Python slice() function
  • Python Return Outside Function
Читайте также:  Название документа

Источник

Understanding Python self Variable with Examples

Python self variable is used to bind the instance of the class to the instance method. We have to explicitly declare it as the first method argument to access the instance variables and methods. This variable is used only with the instance methods.

In most of the Object-Oriented programming languages, you can access the current object in a method without the need for explicitly having it as a method parameter. For example, we can use “this” keyword to access the current object in Java program. But, in Python we have to explicitly declare the object instance as “self” variable.

Python self is a keyword?

Python self variable is not a reserved keyword. But, it’s the best practice and convention to use the variable name as “self” to refer to the instance.

Python self variable Example

Let’s say we have a Dog class defined as below.

class Dog: def __init__(self, breed): self.breed = breed def bark(self): print(f' is barking.') d = Dog('Labrador') d.bark()

Output: Labrador is barking.

  • The __init__() function is defined with two variables but when we are creating the Dog instance, we have to provide only one argument. The “self” is automatically assigned to the newly created instance of Dog class.
  • The bark() method has only one argument – “self” – which gets bind to the Dog instance that calls this method. That’s why we are not passing any argument when calling the bark() method.
  • If we have to access any instance variable in the function, we can use the dot operator.

Can we skip “self” variable?

What if the instance method doesn’t need to access instance variables. Can we skip the self variable in this case?

Let’s find out with a simple example.

class Dog: def bark(): print('Barking') d = Dog() print("Done")

If you will run the above code, there won’t be any error. But, we are not calling the bark() method. Let’s see what happens when we try to call the bark() method.

Читайте также:  Error code 1603 or java update did not complete

Python Class Method Without Self Error

We are getting error as the bark() method accepts 0 argument but we provided 1. It’s because when we are calling d.bark() , the “d” instance is automatically passed as the first argument to the bark() instance method.

But, if we access the bark() instance method through class reference then it will work fine. So, calling Dog.bark() will not cause any errors.

Similar variables for Class Method and Static Method?

The same behavior is present with the Class methods too. The only difference is that the convention is to use “cls” as the variable name for the Class reference.

class Dog: @classmethod def walk(cls): print('Dog is Walking') Dog.walk()

However, it’s not required with a static method. Because, the static methods are self sufficient functions and they can’t access any of the class variables or functions directly.

Let’s look at a complete example with self and cls variables and a static method without any arguments.

class Dog: def __init__(self, breed): self.breed = breed @classmethod def walk(cls): print('Dog is Walking') # instance method def bark(self): print(f' is barking.') @staticmethod def add(x, y): return x + y Dog.walk() d = Dog('Labrador') d.bark() print(Dog.add(10, 20))
Dog is Walking Labrador is barking. 30

Quick Example to Break the Convention

This example is just to show you that it’s not mandatory to use the variable name as “self” and “cls”. In real programming, always stick to this convention.

class Dog: @classmethod def walk(myclass): print('Dog is Walking') # instance method def bark(myobject): print('Dog is Barking.') Dog.walk() d = Dog() d.bark()

The “self” variable is bound to the current instance

The self variable gives us access to the current instance properties. We can confirm this with a simple example by creating two different instances of the Dog class.

class Dog: def __init__(self, b): self.breed = b def bark(self): print(f' is Barking.') d1 = Dog('Labrador') d2 = Dog('Husky') d1.bark() d2.bark()
Labrador is Barking. Husky is Barking.

Why not make “self” variable implicit?

There had been a lot of suggestions to make the “self” variable a reserved keyword and implicitly available to the instance method. But, the suggestion was rejected by “Guido van Rossum”. You can read about them here and here.

Источник

Оцените статью