how to self-reference a class in python?

  • Last Update :
  • Techknowledgy :

self represents the instance of the class. By using the “self”  we can access the attributes and methods of the class in python. It binds the attributes with the given arguments.The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method belongs be passed automatically, but not received automatically: the first parameter of methods is the instance the method is called on.,self is parameter in Instance Method and user can use another parameter name in place of it. But it is advisable to use self because it increases the readability of code, and it is also a good programming practice.,WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri,Self must be provided as a First parameter to the Instance method and constructor. If you don’t provide it, it will cause an error.

Address of self = 140124194801032
Address of class object = 140124194801032

Model is audi a4
color is blue
Model is ferrari 488
color is green

we have used another parameter name in place of self

Suggestion : 2

While this, as other answers have pointed out, is not a problem due to the dynamic typing, in fact, for Python3, this is a very real issue when it comes to type annotations. And this will not work (note a type annotation of the method argument):

class A:
   def do_something_with_other_instance_of_a(self, other: A):
   print(type(other).__name__)

instance = A()
other_instance = A()

instance.do_something_with_other_instance_of_a(other_instance)

results in:

   def do_something_with_other_instance_of_a(self, other: A):
      NameError: name 'A'
   is not defined

"Declaration":

class Node(object):
   data = None # str
left = None # Node object or None
right = None # Node object or None

Usage:

root = Node()
root.data = "foo"

b = Node()
b.data = "bar"
root.left = b

z = Node()
z.data = "zot"
root.right = z

I think this might be helpful

from typing_extensions
import Self

class Node:
   ""
"Binary tree node."
""

def __init__(self, left: Self, right: Self):
   self.left = left
self.right = right

As others have mentioned, you can also use string literals. But it comes to problem when you have multiple type hints.

# python 3.10
var: str | int

And then you write something like

class Node:
   def __init__(self,
      var: 'Node' | SomeClass):
   self.var =
   var

How would I equivalently create this in python?

class node(object):
   def __init__(self, data, left, right):
   self.data = data
self.left = left
self.right = right

This question deserves a revamp for 2021. Let's get some code then run through a breakdown.

from __future__
import annotations
from dataclasses
import dataclass

@dataclass
class Node:
   data: int
left: Node
right: Node

Suggestion : 3

self is also used to refer to a variable field within the class. Let’s take an example and see how it works:,self is used in different places and often thought to be a keyword. But unlike in C++, self is not a keyword in Python.,The self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in python. It binds the attributes with the given arguments. The reason why we use self is that Python does not use the ‘@’ syntax to refer to instance attributes. Join our Master Python programming course to know more. In Python, we have methods that make the instance to be passed automatically, but not received automatically.,self is a parameter in function and the user can use a different parameter name in place of it. Although it is advisable to use self because it increases the readability of code.

Example:

class food():

   # init method or constructor
def __init__(self, fruit, color):
   self.fruit = fruit
self.color = color

def show(self):
   print("fruit is", self.fruit)
print("color is", self.color)

apple = food("apple", "red")
grapes = food("grapes", "green")

apple.show()
grapes.show()

Output:

Fruit is apple
color is red
Fruit is grapes
color is green

self is also used to refer to a variable field within the class. Let’s take an example and see how it works:

class Person:

   # name made in constructor
def __init__(self, John):
   self.name = John

def get_person_name(self):
   return self.name

Suggestion : 4

However, since the class is just a blueprint, self allows access to the attributes and methods of each object in python. This allows each object to have its own attributes and methods. Thus, even long before creating these objects, we reference the objects as self while defining the class.,There is no explicit variable declaration in Python. They spring into action on the first assignment. The use of self makes it easier to distinguish between instance attributes (and methods) from local variables.,We know that class is a blueprint for the objects. This blueprint can be used to create multiple numbers of objects. Let's create two different objects from the above class.,The self keyword is used to represent an instance (object) of the given class. In this case, the two Cat objects cat1 and cat2 have their own name and age attributes. If there was no self argument, the same class couldn't hold the information for both these objects.

In object-oriented programming, whenever we define methods for a class, we use self as the first parameter in each case. Let's look at the definition of a class called Cat.

class Cat:
   def __init__(self, name, age):
   self.name = name
self.age = age

def info(self):
   print(f "I am a cat. My name is {self.name}. I am {self.age} years old.")

def make_sound(self):
   print("Meow")

We know that class is a blueprint for the objects. This blueprint can be used to create multiple numbers of objects. Let's create two different objects from the above class.

cat1 = Cat('Andy', 2)
cat2 = Cat('Phoebe', 3)

So, why do we need to do this? Let's take a simple example to begin with. We have a Point class which defines a method distance to calculate the distance from the origin.

class Point(object):
   def __init__(self, x = 0, y = 0):
   self.x = x
self.y = y

def distance(self):
   ""
"Find distance from origin"
""
return (self.x ** 2 + self.y ** 2) ** 0.5

Point.distance and p1.distance in the above example are different and not exactly the same.

>>> type(Point.distance)
<class 'function'>
   >>> type(p1.distance)
   <class 'method'>

By now you are clear that the object (instance) itself is passed along as the first argument, automatically. This implicit behavior can be avoided while making a static method. Consider the following simple example:

class A(object):

   @staticmethod
def stat_meth():
   print("Look no self was passed")

Suggestion : 5

The new operator is essential to dynamic memory allocation. Operator new takes as an operand the type of the object being dynamically allocated and returns a reference to an object of that type. For example, the statement,The following sections discuss lists, stacks, queues and trees. These data structures are created and maintained with dynamic memory allocation and self-referential classes.,allocates the appropriate amount of memory to store a Node and stores a reference to this object in nodeToAdd. If no memory is available, new throws an OutOfMemoryException. The constructor argument 10 specifies the Node object's data.,Figure 25.1. Self-referential Node class declaration.

 1 // Fig. 25.1: Fig25_01.cs
 2 // A self-referential class.
 3 class Node
 4 {
    5 private int data; // store integer data
    6 private Node next; // store reference to next Node
    7
    8 public Node(int dataValue)
    9 {
       10 // constructor body
       11
    } // end constructor
    12
    13 public int Data
    14 {
       15 get
       16 {
          17 // get body
          18
       } // end get
       19 set
       20 {
          21 // set body
          22
       } // end set
       23
    } // end property Data
    24
    25 public Node Next
    26 {
       27 get
       28 {
          29 // get body
          30
       } // end get
       31 set
       32 {
          33 // set body
          34
       } // end set
       35
    } // end property Next
    36
 } // end class Node
1._
 1 // Fig. 25.1: Fig25_01.cs
 2 // A self-referential class.
 3 class Node
 4 {
    5 private int data; // store integer data
    6 private Node next; // store reference to next Node
    7
    8 public Node(int dataValue)
    9 {
       10 // constructor body
       11
    } // end constructor
    12
    13 public int Data
    14 {
       15 get
       16 {
          17 // get body
          18
       } // end get
       19 set
       20 {
          21 // set body
          22
       } // end set
       23
    } // end property Data
    24
    25 public Node Next
    26 {
       27 get
       28 {
          29 // get body
          30
       } // end get
       31 set
       32 {
          33 // set body
          34
       } // end set
       35
    } // end property Next
    36
 } // end class Node

The new operator is essential to dynamic memory allocation. Operator new takes as an operand the type of the object being dynamically allocated and returns a reference to an object of that type. For example, the statement

Node nodeToAdd = new Node(10);

Suggestion : 6

Instance method objects have attributes, too: m.__self__ is the instance object with the method m(), and m.__func__ is the function object corresponding to the method.,The other kind of instance attribute reference is a method. A method is a function that “belongs to” an object. (In Python, the term method is not unique to class instances: other object types can have methods as well. For example, list objects have methods called append, insert, remove, sort, and so on. However, in the following discussion, we’ll use the term method exclusively to mean methods of class instance objects, unless explicitly stated otherwise.),There is no shorthand for referencing data attributes (or other methods!) from within methods. I find that this actually increases the readability of methods: there is no chance of confusing local variables and instance variables when glancing through a method.,Now f, g and h are all attributes of class C that refer to function objects, and consequently they are all methods of instances of C — h being exactly equivalent to g. Note that this practice usually only serves to confuse the reader of a program.

def scope_test():
   def do_local():
   spam = "local spam"

def do_nonlocal():
   nonlocal spam
spam = "nonlocal spam"

def do_global():
   global spam
spam = "global spam"

spam = "test spam"
do_local()
print("After local assignment:", spam)
do_nonlocal()
print("After nonlocal assignment:", spam)
do_global()
print("After global assignment:", spam)

scope_test()
print("In global scope:", spam)
After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam
class ClassName:
<statement-1>
   .
   .
   .
   <statement-N>
class MyClass:
   ""
"A simple example class"
""
i = 12345

def f(self):
   return 'hello world'
x = MyClass()
def __init__(self):
   self.data = []