首页 > 解决方案 > Python 3 中的 __init__ 和 self

问题描述

有谁知道__init__和 self 在 Python 中的含义 - 一个简单易懂的解释。
我有一个基本的了解,并希望扩大。这样的代码将用于何处?

标签: python

解决方案


自己

该词self用于表示类的实例。通过使用“self”关键字,我们可以访问python中类的属性和方法。

初始化方法

_init__是 python 类中的保留方法。在面向对象的术语中,它被称为构造函数。当从类创建对象时调用此方法,它允许类初始化类的属性。例子

找出宽度(b = 120),长度(l = 160)的矩形字段的成本。每 1 平方单位成本 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

推荐阅读