如何理解python对象
作者:Ly 时间:2022-09-04 06:58:54
类(class)抽象的概念,比如说人类、鸟类、水果、是一个总的称呼,没有具体到某个物体;
对象(object,指具体实例,instance);
给对象增加一个实例变量
# 增加一个skills实例变量
p.skills = ['programming','writing']
print(p.skills)
#删除p对象的name实例变量,而不是删除类中变量,新建一个对象,name实例变量还是构造函数默认的。
del p.name
# print(p.name) 会报错
Python 允许通过对象访问类变量 ,但如果程序通过对象尝试对类变量赋值,此时性质就变了一Python 是动态语言,赋值语句往往意味着定义新变量。因此,如果程序通过对象对类变量赋值,其实不是对“类变量赋值”,而是定义新的实例变量 。例如如下程序 。
class Inventory:
#定义两个变量
quantity = 2000
item = '鼠标'
#定义实例方法
def change(self,item,quantity):
self.item = item
self.quantity = quantity
#创建Inventory对象
iv = Inventory()
iv.change('显示器',500)
#访问iv的item和quantity实例变量
print(iv.item) #显示器
print(iv.quantity) #500
#访问Inventotry的item和quantity类变量
print(Inventory.item) #鼠标
print(Inventory.quantity) #2000
观点扩展:
Python的面向对象,可以简单理解为你处理的东西都是“对象”。变量是指向一个对象的,变量名称是一个对象,相关的是namespace这个概念。类代表一类东西,是个对象。class下面的instance就是类的具体表现,相当于具备某一特征的个体,这些都是对象。
来源:https://www.py.cn/faq/python/19046.html
标签:python,对象
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
如何创建 Firefox 的 Jetpack 扩展
2009-10-13 20:55:00
![](https://img.aspxhome.com/file/UploadPic/200910/13/jetpack01-44s.png)
最简单的tab切换实例代码
2023-08-22 08:38:59
![](https://img.aspxhome.com/file/2023/6/56006_0s.jpg)
php中加密解密DES类的简单使用方法示例
2023-09-07 23:28:44
![](https://img.aspxhome.com/file/2023/3/554131_0s.png)
[译]在线广告及其在网页设计中的重要性
2009-02-06 13:36:00
![](https://img.aspxhome.com/file/UploadPic/20092/6/001-22s.jpg)
Linux下python与C++使用dlib实现人脸检测
2023-06-13 16:13:20
![](https://img.aspxhome.com/file/2023/9/59829_0s.jpg)
python requests 库请求带有文件参数的接口实例
2022-04-23 09:12:10
![](https://img.aspxhome.com/file/2023/2/103692_0s.jpg)
python 实现list或string按指定分段
2023-10-30 02:04:20
python编程简单几行代码实现视频转换Gif示例
2021-09-02 03:34:13
![](https://img.aspxhome.com/file/2023/1/100991_0s.gif)
Python OpenCV之常用滤波器使用详解
2023-02-07 22:18:25
![](https://img.aspxhome.com/file/2023/9/81589_0s.jpg)
pyecharts绘制时间轮播图柱形图+饼图+玫瑰图+折线图
2022-01-18 13:19:47
![](https://img.aspxhome.com/file/2023/0/79800_0s.png)
Oracle中sys和system的区别小结
2009-11-10 20:36:00
15个滑动门效果CSS导航菜单实例教程
2010-02-20 13:02:00
![](https://img.aspxhome.com/file/UploadPic/20102/20/150916p3l-29s.png)
python 将日期戳(五位数时间)转换为标准时间
2021-09-14 06:36:47
![](https://img.aspxhome.com/file/2023/5/82525_0s.png)
寻找Dreamweaver鲜为人知的小秘诀
2008-04-28 12:10:00
ORACLE 自动提交问题
2023-07-24 10:43:13
![](https://img.aspxhome.com/file/2023/5/63355_0s.jpg)
python字符串的一些常见实用操作
2022-05-08 15:53:30
![](https://img.aspxhome.com/file/2023/5/71375_0s.gif)
为什么要进行CSS缩写?
2007-10-29 12:56:00
![](https://img.aspxhome.com/file/UploadPic/200710/29/2007102913194943s.gif)
python开发一款翻译工具
2022-01-19 07:28:43
![](https://img.aspxhome.com/file/2023/5/72035_0s.png)
Asp Oracle存储过程返回结果集的代码
2011-04-10 11:16:00
python 对key为时间的dict排序方法
2021-03-22 17:09:59