Object-Oriented Python

本文深入探讨Python中类的定义方法,包括空类的创建、类中函数使用self参数的原因,以及对象属性的存储与访问方式。通过具体示例,讲解如何避免常见错误,如在初始化函数中正确使用self及属性赋值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.define an empty class

use pass to avoid error, python doesn’t let us define classes or functions when they are empty
在这里插入图片描述

2. 类中函数的第一个参数总是对象本身,写作self

在这里插入图片描述

3. attributes

The power of objects is in their ability to store data,and the data is stored inside objects using attributes. You can think of attributes like special variables that belongs to a particular class. When we instantiate an object, most of the time we specify the data that we want to store inside that object.
在这里插入图片描述

4. example

1.在这里插入图片描述make sure you use self.data, otherwise you are not creating an attribute, you’re just assigning to a variable. To access our attribute from within the method, we need to use self.data
2.以下例子出现报错: object() takes no parameters找了很久的错误结果发现初始化函数必须是左右两条下划线**init**在这里插入图片描述在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值