Python面向对象之类和对象属性的增删改查操作示例
作者:我是马克思小清新 时间:2021-11-06 14:20:40
本文实例讲述了Python面向对象之类和对象属性的增删改查操作。分享给大家供大家参考,具体如下:
一、类属性的操作
# -*- coding:utf-8 -*-
#! python2
class Chinese:
country = 'China'
def __init__(self,name):
self.name = name
def play_ball(self,ball):
print('%s play %s' %(self.name,ball))
#查看属性
print(Chinese.country)
#修改属性
Chinese.country = 'Japan'
print(Chinese.country)
p1 = Chinese('alex')
print(p1.__dict__)
print(p1.country)
#增加属性
Chinese.dang = '脚本之家'
print(Chinese.dang)
print(p1.dang)
#删除属性
del Chinese.dang
del Chinese.country
print(Chinese.__dict__)
运行结果:
China
Japan
{'name': 'alex'}
Japan
脚本之家
脚本之家
{'__module__': '__main__', 'play_ball': <function play_ball at 0x01AAB7B0>, '__doc__': None, '__init__': <function __init__ at 0x01AAB830>}
二、对象属性的操作
# -*- coding:utf-8 -*-
#! python2
class Chinese:
country = 'China'
def __init__(self,name):
self.name = name
def play_ball(self,ball):
print('%s play %s' %(self.name,ball))
def test():
print("对象方法的属性")
p1 = Chinese('alex')
print(p1.__dict__)
#查看属性
print(p1.name)
print(p1.play_ball)
#增加属性
p1.age = 18
print(p1.__dict__)
print(p1.age)
p1.test = test #将外界的方法作为函数属性加入类中
print(p1.__dict__)
p1.test()
#修改属性
p1.age = 19
print(p1.__dict__)
print(p1.age)
#删除属性
del p1.age
print(p1.__dict__)
运行结果:
{'name': 'alex'}
alex
<bound method Chinese.play_ball of <__main__.Chinese instance at 0x01AE9DA0>>
{'age': 18, 'name': 'alex'}
18
{'test': <function test at 0x01AEB7F0>, 'age': 18, 'name': 'alex'}
对象方法的属性
{'test': <function test at 0x01AEB7F0>, 'age': 19, 'name': 'alex'}
19
{'test': <function test at 0x01AEB7F0>, 'name': 'alex'}
希望本文所述对大家Python程序设计有所帮助。
来源:https://blog.csdn.net/qq_33531400/article/details/79879414
标签:Python,面向对象,类,对象
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
[翻译]标记语言和样式手册 Chapter 10 应用CSS
2008-02-02 18:44:00
![](https://img.aspxhome.com/file/UploadPic/20082/2/200822192227241s.jpg)
pandas DataFrame索引行列的实现
2023-12-16 09:52:55
一个js自动完成功能源码
2011-06-06 07:42:00
server.mappath方法详解
2023-07-05 08:07:48
PHP header()函数使用详细(301、404等错误设置)
2023-11-02 17:28:23
详解pycharm的python包opencv(cv2)无代码提示问题的解决
2022-01-10 06:45:34
![](https://img.aspxhome.com/file/2023/5/103755_0s.png)
详解Python装饰器的四种定义形式
2022-06-20 13:35:04
python目标检测给图画框,bbox画到图上并保存案例
2023-03-07 07:47:52
使用Python解决常见格式图像读取nii,dicom,mhd
2021-11-14 23:36:59
Oracle查看逻辑读、物理读资源占用排行的SQL语句
2023-06-25 23:53:53
Python命令行参数解析工具 docopt 安装和应用过程详解
2022-01-15 05:31:05
Python 3 判断2个字典相同
2021-05-19 23:58:50
javascript创建数组的最简代码
2013-09-01 21:43:04
FrontPage2002简明教程三:网页布局
2008-09-17 11:19:00
![](https://img.aspxhome.com/file/UploadPic/200810/17/2008101711222914s.jpg)
使用SQL Server 2008中对象相关性
2008-12-12 06:36:00
tensorflow训练中出现nan问题的解决
2023-02-10 09:34:09
Django与DRF结合的全局异常处理方案详解
2021-05-19 22:53:16
将不规则的Python多维数组拉平到一维的方法实现
2023-11-05 19:47:15
![](https://img.aspxhome.com/file/2023/2/63872_0s.png)
asp下以Json获取中国天气网天气的代码
2011-03-06 11:01:00
界面设计10条可用性方面的启发
2010-04-06 17:22:00
![](https://img.aspxhome.com/file/UploadPic/20104/6/heuristics-95s.gif)