Python.面向对象---类和对象属性的增删改查

一,类属性的操作

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__)

二,对象属性的操作

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__)


猜你喜欢

转载自blog.csdn.net/qq_33531400/article/details/79879414