SoFunction
Updated on 2025-03-01

Summary of examples of common special methods in Python

This article describes the common special methods used in Python. Share it for your reference, as follows:

1 __init__ and __new__

__init__Methods are used to initialize class instances;__new__Methods are used to create class instances.

Main differences:

1).__init__ is usually used to initialize a new instance, controlling the initialization process, which occurs after the class instance is created. It is an instance-level method.

2).__new__ is usually used to control the process of generating a new instance. It is a class-level method.

__new__Specific role:

1) Inherit some immutable class (such as int, str, tuple), provide a way to customize the instantiation process of these classes

2) Implement custom metaclass

Example: Implementation always returns positive numbers

class PositiveInteger(int): #Inheritance class int  def __new__(cls, value):
    return super().__new__(cls, abs(value)) #Return the __new__ method of the parent classi = PositiveInteger(-3) #Class instantiationprint(i)
3

Note:

about__init__Method: The first parameter must beself; No return value

about__new__method:

1) Only new classes inherited from object have__new__

2) __new__At least one parameter cls represents the class to be instantiated. This parameter is automatically provided by the Python interpreter when instantiated.

3) __new__There must be a return value, and the instantiated instance must be returned (that is,__init__ofself), can return to the parent class__new__The instance that came out, or is directly object__new__An example that came out

2 __del__ method

When all references to the object are deleted, the method is triggered, the code is as follows:

class Testdel():
  def __del__(self):
    print("using __del__")
t = Testdel()
t1 = t
del t1
del t
using __del__

3 __str__ and __repr__

__repr__and__str__Both methods are used for display.__str__It is for users, and__repr__For programmers

definition__repr__Simple way: define__str__After that, assign the value to__repr__,as follows:

__repr__ = __str__

4 Attribute Access

__getattr__(self, name): The behavior when a user tries to obtain a non-existent property (name)

__getattribute__(self, name): Behavior when a class's attribute is accessed

__setattr__(self, name, value): Behavior when an attribute is set

__delattr__(self, name): Behavior when an attribute is deleted

The dead loop trap:

class Rectangle:
  def __init__(self, width=0, height=0):
     = width
     = height
  def __setattr__(self, name, value):
    if name == ‘square':
       = value
       = value
    else:
       = value
  def getArea(self):
    return  * 
r = Rectangle(3,4)

Instantiationr = Rectangle(3, 4)There will be a vicious cycle because__init__The setting attribute value appears inside, jump to__setattr__The inside e = valueThis sentence means continuing the assignment operation = width, so it enters a vicious cycle. Solution:

1) Change the else clause to:super().__setattr__(name, value)

2) Change the else clause to:self.__dict__[name] = value

5 Descriptor: Assign an instance of a class of some special type to another class's properties

Special types refer to:

__get__(self, instance, owner): Access the attribute and return the value of the attribute

__set__(self, instance, value): Used to set properties and do not return anything

__delete__(self, instance): Delete attributes and return no content

self: An instance of the descriptor class itself,instance: An instance of the owner class,owner: Owner, class itself

class MyDecriptor:
  def __get__(self, instance, owner): #Understand the meaning of self instance owner    print(‘getting...', self, instance, owner)
  def __set__(self, instance, value):
    print(‘setting…',self, instance,value)
  def __delete__(self, instance):
    print(‘deleting…',self, instance)
class Test:
  x = MyDecriptor()
test = Test() #Instantiation
 = ‘X-man'
del 

Readers who are interested in Python related content can view the special topic of this site:Introduction and Advanced Tutorial on Object-Oriented Programming in Python》、《Python data structure and algorithm tutorial》、《Summary of Python function usage tips》、《Summary of Python string operation skills》、《Summary of Python encoding operation skills"and"Python introduction and advanced classic tutorials

I hope this article will be helpful to everyone's Python programming.