Python 類中 self 和 __init__ 方法之間的區別是什麼?\n
self
單詞“self”用於表示類的例項。透過使用“self”關鍵字,我們在 Python 中訪問了類的屬性和方法。
__init__ 方法
“__init__”是 Python 類中的保留方法。在面向物件術語中,它被稱為建構函式。在從類建立物件時呼叫該方法,該方法允許類初始化類的屬性。
示例
找出長方形場地的成本(b = 120,l = 160)。每個平方單位成本 x(2000)盧比
class Rectangle:
def __init__(self, length, breadth, unit_cost=0):
self.length = length
self.breadth = breadth
self.unit_cost = unit_cost
def get_area(self):
return self.length * self.breadth
def calculate_cost(self):
area = self.get_area()
return area * self.unit_cost
# breadth = 120 units, length = 160 units, 1 sq unit cost = Rs 2000
r = Rectangle(160, 120, 2000)
print("Area of Rectangle: %s sq units" % (r.get_area()))輸出
輸出為
Area of Rectangle: 19200 sq units Cost of rectangular field: Rs.38400000
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP