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