首页 > 编程 > Python > 正文

Python面向对象之类和对象属性的增删改查操作示例

2020-01-04 13:49:53
字体:
来源:转载
供稿:网友

本文实例讲述了Python面向对象之类和对象属性的增删改查操作。分享给大家供大家参考,具体如下:

一、类属性的操作

# -*- coding:utf-8 -*-#! python2class 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 = 'VEVB武林网'print(Chinese.dang)print(p1.dang)#删除属性del Chinese.dangdel Chinese.countryprint(Chinese.__dict__)

运行结果:

China
Japan
{'name': 'alex'}
Japan
VEVB武林网
VEVB武林网
{'__module__': '__main__', 'play_ball': <function play_ball at 0x01AAB7B0>, '__doc__': None, '__init__': <function __init__ at 0x01AAB830>}

二、对象属性的操作

# -*- coding:utf-8 -*-#! python2class 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 = 18print(p1.__dict__)print(p1.age)p1.test = test   #将外界的方法作为函数属性加入类中print(p1.__dict__)p1.test()#修改属性p1.age = 19print(p1.__dict__)print(p1.age)#删除属性del p1.ageprint(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程序设计有所帮助。


注:相关教程知识阅读请移步到python教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表