Python面向对象编程:类与对象属性的增删改查详解
本文通过Python代码示例,详细演示了类属性和对象属性的增删改查操作。内容涵盖如何查看、修改、增加及删除类级属性,以及如何对实例对象的属性进行类似操作,包括动态绑定方法。适合希望深入理解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 = '本站'
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相关知识,建议查阅本站专题:《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》以及《Python入门与进阶经典教程》。
希望上述关于Python程序设计的内容阐述能为您提供帮助。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









