[Python Basic Literacy] What are the uses and differences of the self parameter, the __init__ method and the .__str__ method?


brief description

The following is a Markdown table that compares selfand __init__compares from multiple perspectives:__str__

self __init__ __str__
type parameter method method
effect referencing the instance object itself initialize instance Defines the string representation of the instance
function prototype def method(self, ...) def __init__(self, ...) def __str__(self)
return value None (used as parameter) None (for initialization) string
Is it necessary Yes (in instance methods) No (but usually required) No (but required if printing or conversion to string is required)
scenes to be used Access or modify instance properties in instance methods, or call other instance methods Set the initial state when creating a new instance Use when printing an instance or converting an instance to a string

This table provides a basic comparison of self, , __init__and __str__. The exact usage may vary depending on your needs and the design of the class.


In Python, self, __init__and __str__are common elements in class definitions. Their respective purposes and differences are as follows:

  1. self : In Python, selfit is a conventional name used to refer to the instance object itself. When you define a method of a class, the first parameter is usually named self, which represents the instance of the class. Through it self, you can access and modify instance properties, or call other instance methods.

    class MyClass:
        def my_method(self):
            print("This is a method of the instance: ", self)
    
  2. init :__init__is a special method called the constructor method of the class. __init__Methods are automatically calledwhen you create a new instance of a classYou can__init__set the initial state of the instance in the method, such as initializing the properties of the instance.

    class MyClass:
        def __init__(self):
            self.my_attribute = "Hello, world!"
    
  3. str :__str__Also a special method that should return a string representing the instance. The method is calledwhen you useprintthe function to print an instance, or usestrthe function to convert an instance to a string__str__

    class MyClass:
        def __init__(self, my_attribute):
            self.my_attribute = my_attribute
    
        def __str__(self):
            return "MyClass with my_attribute: " + self.my_attribute
    
    my_instance = MyClass("Hello, world!")
    print(my_instance)  # 输出:MyClass with my_attribute: Hello, world!
    

In general, self, __init__and __str__are important elements in the Python class definition, which are used to refer to the instance itself, initialize the instance, and define the string representation of the instance.

prototype

In Python, the function prototypes of , and are usually as selffollows __init__:__str__

  1. self : selfNot a function, but a parameter used in a method of a class to refer to the instance object itself. When defining a method of a class, it is usually given selfas the first parameter:

    def some_method(self, other_arguments):
        # 方法体
    
  2. init :__init__is a special method used to initialize a new instance of a class. Its function prototype is as follows:

    def __init__(self, other_arguments):
        # 方法体
    

    Here, other_argumentsare the other parameters you need to pass to __init__the method.

  3. str :__str__Also a special method used to return a string representing an instance. Its function prototype is as follows:

    def __str__(self):
        # 方法体,返回一个字符串
    

    Note that __str__the method takes no selfarguments other than , and must return a string.

In these function prototypes, selfthe parameter is required because it represents an instance of the class. For __init__the and __str__method, you can add other parameters or modify the return value according to your needs.

scenes to be used

The following are common usage scenarios for self, __init__and __str__in Python:

  1. self : selfUsed as the first parameter in the method of the class to refer to the instance object itself. This allows instance methods to access and modify instance properties, or to call other instance methods. For example, if you are writing a class that represents a bank account, you may need to selfaccess and modify the account's balance using

    class BankAccount:
        def __init__(self, initial_balance):
            self.balance = initial_balance
    
        def deposit(self, amount):
            self.balance += amount
    
        def withdraw(self, amount):
            if amount <= self.balance:
                self.balance -= amount
            else:
                print("Insufficient balance!")
    
  2. init :__init__The method is called when a new instance of the class is created and is used to initialize the state of the instance. For example, if you are writing a class that represents a rectangle, you may need to__init__receive the width and height as parameters in a method and store them as properties of the instance.

    class Rectangle:
        def __init__(self, width, height):
            self.width = width
            self.height = height
    
        def area(self):
            return self.width * self.height
    
  3. str :__str__method is used to define a string representation of an instance, which is useful when printing an instance or converting an instance to a string. For example, if you are writing a class that represents a date, you may need to__str__return a formatted date string in a method.

    class Date:
        def __init__(self, year, month, day):
            self.year = year
            self.month = month
            self.day = day
    
        def __str__(self):
            return f"{
            
            self.year}-{
            
            self.month:02d}-{
            
            self.day:02d}"
    

These are just some basic usage scenarios of self, , __init__and __str__. In fact, you can use them according to your specific needs.

epilogue

Comprehension is an important step towards the next level in our programming learning journey. However, mastering new skills and ideas always takes time and persistence. From a psychological point of view, learning is often accompanied by continuous trial and error and adjustment, which is like our brain gradually optimizing its "algorithm" for solving problems.

That's why when we encounter mistakes, we should see them as opportunities to learn and improve, not just obsessions. By understanding and solving these problems, we can not only fix the current code, but also improve our programming ability and prevent the same mistakes from being made in future projects.

I encourage everyone to actively participate and continuously improve their programming skills. Whether you are a beginner or an experienced developer, I hope my blog can help you in your learning journey. If you find this article useful, you may wish to click to bookmark it, or leave your comments to share your insights and experiences. You are also welcome to make suggestions and questions about the content of my blog. Every like, comment, share and follow is the greatest support for me and the motivation for me to continue to share and create.


Read my CSDN homepage to unlock more exciting content: Bubble's CSDN homepage
insert image description here

Guess you like

Origin blog.csdn.net/qq_21438461/article/details/131368992