python课堂整理34----类的增删改查及实例属性增删改查

一、类的增删改查

类里面定义的函数,第一个参数一定要写 self ,因为class的特殊性

定义类名:首字母大写

函数属性命名:动词加名词(即干什么事)

class Chinese:
    country = 'China'
    def __init__(self,name):
        self.name = name

    def play_ball(self, ball):
        print("%s 正在打%s"%(self.name,ball))

p1 = Chinese('sb') #实例化

print(Chinese.country) #查
Chinese.country = 'CHINESE' #改
print(p1.country) #查
Chinese.dang = 'gong chan党' #增加
print(p1.dang)  #p1也能查看dang,因为p1会到类里去找dang这个属性

 

class Chinese:
    country = 'China'
    def __init__(self,name):
        self.name = name

    def play_ball(self, ball):
        print("%s 正在打%s"%(self.name,ball))

p1 = Chinese('sb') #实例化


Chinese.dang = 'gong chan党' #增加
print(p1.dang)
del Chinese.dang #删
print(p1.dang) #删掉后再调用,所以会报错

class Chinese:
    country = 'China'
    def __init__(self,name):
        self.name = name

    def play_ball(self, ball):
        print("%s 正在打%s"%(self.name,ball))

p1 = Chinese('sb') #实例化
#创建函数属性
def eat(self, food):
    print('%s正在吃%s'%(self.name, food))
Chinese.eat_food = eat  #增加一个函数属性

p1.eat_food('屎') #调用

def test(self):
    print('我被修改了qaq')

Chinese.play_ball = test #修改函数属性
p1.play_ball()

二、实例属性的增删改查

#查

class Chinese:
    country = 'China'
    def __init__(self,name):
        self.name = name

    def play_ball(self, ball):
        print("%s 正在打%s"%(self.name,ball))

p1 = Chinese('sb') #实例化
print(p1.__dict__)
#查看
print(p1.name)
print(p1.play_ball)

  

#增

class Chinese:
    country = 'China'
    def __init__(self,name):
        self.name = name

    def play_ball(self, ball):
        print("%s 正在打%s"%(self.name,ball))

p1 = Chinese('sb') #实例化
print(p1.__dict__)
#增加
p1.age = 18
print(p1.__dict__)
print(p1.age)

注意:不要修改底层的属性字典,即 p1.__dict__   

#p1.__dict__['sex'] = 'male'

#删除

class Chinese:
    country = 'China'
    def __init__(self,name):
        self.name = name

    def play_ball(self, ball):
        print("%s 正在打%s"%(self.name,ball))

p1 = Chinese('sb') #实例化
print(p1.__dict__)
#增加
p1.age = 18
print(p1.__dict__)
print(p1.age)
#删除
del p1.age
print(p1.__dict__)

三、对象和实例属性

可以把class当做最外层的函数,是一个作用域

#定义一个类,只当一个作用域,类似于c语言中的结构体
class MyData: pass x = 10 y = 20 MyData.x = 1 MyData.y = 2 print(x, y) print(MyData.x,MyData.y) print(MyData.x + MyData.y)

类中的数据属性及类外的变量

class Chinese:
    country = 'China'
    def __init__(self, name):
        self.name  = name

    def play_ball(self,ball):
        print('%s正在打%s'%(self.name, ball))

p1 = Chinese('sb')
print(p1.country)
p1.country = '华夏'  #相当于在实例字典中添加了一个数据属性
print('类的---->',Chinese.country)
print('实例的--->', p1.country)

遵循点的调用方式,就在类的内部查找

在类的内部定义的数据属性,就跑到类字典去了

在实例内部定义的数据属性,就跑到实例字典去了

不加点就跟类无关,跟实例无关

country = '中国'
class Chinese:
    country = 'China'
    def __init__(self, name):
        self.name  = name
        print('--->',country)  #不是点的调用方式,所以直接去类外去找

    def play_ball(self,ball):
        print('%s正在打%s'%(self.name, ball))

p1 = Chinese('sb')
print(p1.country)

  

 

 

一个奋斗中的产品小白
原文地址:https://www.cnblogs.com/dabai123/p/11438467.html