The __init__ and self are two keywords in python, which performs a vital role in the application.
__init__和self是python中的兩個關鍵字,在應用程序中起著至關重要的作用。
To begin with, it is important to understand the concept of class and object.
首先,了解類和對象的概念很重要。
Class
類
In Object-oriented programming, a class is a blueprint for creating objects of a particular data structure, provisioning the initial values for the state, and implementation of a behavior.
在面向對象的編程中,類是用于創建特定數據結構的對象,提供狀態的初始值以及實現行為的藍圖。
The user-defined objects are created using the class keyword.
用戶定義的對象是使用class關鍵字創建的。
Object
目的
It is a basic unit of Object-Oriented Programming and each object is an instance of a particular class or subclass with class's methods or procedures and data variables.
它是面向對象編程的基本單元,每個對象都是具有類的方法或過程以及數據變量的特定類或子類的實例。
With the above understanding,
基于以上理解,
__在里面__ (__init__)
__init__ is a reserved method in python classes. It is used to create an object of a class, something like a constructor in Java. This method when called creates an object of the class and it allows the class to initialize the attributes of the class.
__init__是python類中的保留方法。 它用于創建類的對象,類似于Java中的構造函數。 調用此方法時,將創建該類的對象,并允許該類初始化該類的屬性。
Example usage of __init__:
__init__的用法示例:
# A Sample class with init method
class Country:
# init method or constructor
def __init__(self, name):
self.name = name
# Sample Method
def hello(self):
print('Hello, my name is', self.name)
c = Country('India')
c.hello()
Output
輸出量
Hello, my name is India
In the above example, the line c = Country('India') invokes the method __init__ and creates an object c, which can then further invoke the method hello().
在上面的示例中,行c = Country('India')調用方法__init__并創建對象c ,然后可以進一步調用方法hello() 。
自 (self)
The word self is used to represent the instance of the class. Using self, the attributes and the methods of the class can be accessed.
單詞self用于表示類的實例。 使用self ,可以訪問類的屬性和方法。
Example usage of self:
自我用法示例:
class Country:
# init method or constructor
def __init__(self, name):
self.name = name
# Sample Method
def hello(self):
print('Hello, my name is', self.name)
Output
輸出量
No output
In the above example, name is the attribute of the class Country and it can be accessed by using the self keyword.
在上面的示例中, name是Country類的屬性,可以使用self關鍵字對其進行訪問。
翻譯自: https://www.includehelp.com/python/what-__init__-and-self-do-in-python.aspx