python - Python 3 中的 __init__ 和 self
问题描述
有谁知道__init__
和 self 在 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
推荐阅读
- flutter - 如何在 ListView 中拉伸 Container。扑
- react-native - 我如何在更改时从文本输入更新字段反应本机
- angular - ngb-panel 上的 cardClass 是否支持封装?
- mysql - 定义函数时如何修复 SQL 语法错误
- c++ - 我们应该在函数中用 constexpr 定义变量吗
- dask - 从连续产生的分散数据中更新 dask 数组
- docker - 将没有源代码的 Web 应用程序容器化?
- graph-databases - 插入大数据时出现“gRPC 消息超出”错误
- c# - 删除我的程序后,系统托盘中隐藏图标的窗口保持打开状态图标
- rust - Tokio UDP 服务器