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

yipeiwu_com6年前Python基础

本文实例讲述了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 = '【听图阁-专注于Python设计】'
print(Chinese.dang)
print(p1.dang)
#删除属性
del Chinese.dang
del Chinese.country
print(Chinese.__dict__)

运行结果:

China
Japan
{'name': 'alex'}
Japan
【听图阁-专注于Python设计】
【听图阁-专注于Python设计】
{'__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相关内容感兴趣的读者可查看本站专题:《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python中的左斜杠、右斜杠(正斜杠和反斜杠)

首先,"/"左倾斜是正斜杠,"\"右倾斜是反斜杠,可以记为:除号是正斜杠一般来说对于目录分隔符,Unix和Web用正斜杠/,Windows用反斜杠,但是现在Windows (一)目录中...

深入分析在Python模块顶层运行的代码引起的一个Bug

然后我们在Interactive Python prompt中测试了一下: >>> import subprocess >>> subproc...

探究python中open函数的使用

探究python中open函数的使用

最近,开始学习python的开发,遇到了一点文件操作的问题,探究一下open函数的使用。 一、open()的函数原型 open(file, mode=‘r', buffering=-1,...

Python中矩阵创建和矩阵运算方法

Python中矩阵创建和矩阵运算方法

矩阵创建 1、from numpyimport *; a1=array([1,2,3]) a2=mat(a1) 矩阵与方块列表的区别如下: 2、data2=mat(ones((2,4)...

python3实现字符串操作的实例代码

python3字符串操作 x = 'abc' y = 'defgh' print(x + y) #x+y print(x * 3) #x*n print(x...