directory title
brief description
The following is a Markdown table that compares self
and __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:
-
self : In Python,
self
it 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 namedself
, which represents the instance of the class. Through itself
, 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)
-
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!"
-
str :
__str__
Also a special method that should return a string representing the instance. The method is calledwhen you useprint
the function to print an instance, or usestr
the 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 self
follows __init__
:__str__
-
self :
self
Not 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 givenself
as the first parameter:def some_method(self, other_arguments): # 方法体
-
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_arguments
are the other parameters you need to pass to__init__
the method. -
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 noself
arguments other than , and must return a string.
In these function prototypes, self
the 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:
-
self :
self
Used 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 toself
access and modify the account's balance usingclass 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!")
-
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
-
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