本文實例講述了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程序設計有所幫助。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。