日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python中的__init__和self是做什么的?

發(fā)布時間:2025/3/11 python 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python中的__init__和self是做什么的? 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

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.

在面向對象的編程中,類是用于創(chuàng)建特定數(shù)據(jù)結構的對象,提供狀態(tài)的初始值以及實現(xiàn)行為的藍圖。

The user-defined objects are created using the class keyword.

用戶定義的對象是使用class關鍵字創(chuàng)建的。

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.

它是面向對象編程的基本單元,每個對象都是具有類的方法或過程以及數(shù)據(jù)變量的特定類或子類的實例。

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類中的保留方法。 它用于創(chuàng)建類的對象,類似于Java中的構造函數(shù)。 調用此方法時,將創(chuàng)建該類的對象,并允許該類初始化該類的屬性。

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__并創(chuàng)建對象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

總結

以上是生活随笔為你收集整理的Python中的__init__和self是做什么的?的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。