类属性与实例属性

类属性:

#-------------类属性的增删改查------------
class People:
    country = 'China'
    def __init__(self,name):
        self.name=name
    def eat_food(self,food):
        print('%s正在吃%s'%(self.name,food))
    def play_ball(self,ball):
        print('%s正在玩%s'%(self.name,ball))
    def say_word(self,word):
        print('%s正在说%s'%(self.name,word))
# #查看类属性
print(People.country)
#实例化一个对象
P1=People('dashu')
P1.country
P1.eat_food('粽子')
P1.play_ball('lanqiu')

#修改类属性
People.country='CHINA'
print(People.country)
#删除类属性
del People.country
print(People.country)#报错 因为country属性已经被删掉
#增加类属性
People.country = 'china'
People.count='100'
print(People.count)

def play_PC(self,game):
    print('%s正在玩%s'%(self.name,game))
People.PC=play_PC
P1.PC('xxl')

实例属性:

# #--------------实例属性增删改查---------------
class People:
    country = 'China'
    def __init__(self,name):
        self.name=name
    def eat_food(self,food):
        print('%s正在吃%s'%(self.name,food))
p1 = People('guoguo')
print(p1.__dict__)

#查看实例属性
print(p1.name)
p1.eat_food('粽子')#访问类

#增加数据属性
p1.age=18
print(p1.__dict__)
print(p1.age)

# #不要修改底层的属性结构:
# p1.__dict__['sex']='female'
# print(p1.__dict__)
# print(p1.sex)

#修改
p1.age=99
print(p1.__dict__)
print(p1.age)
#删除
del p1.age
print(p1.__dict__)
# ----------------区分哪些是调用类实行和实例属性 哪些不是-----------------
class People:
    country = 'Ch'
    def __init__(self,name):
        self.name=name
    def eat_food(self,food):
        print('%s正在吃%s'%(self.name,food))
p1=People('dashu')
print(p1.country)
p1.country='JP'
print(People.country)
print(p1.country)

#报错 p1.age仅在类里面找country 找不到则报错
country = 'CA'
class People:
    def __init__(self, name):
        self.name = name
    def eat_food(self, food):
        print('%s正在吃%s' % (self.name, food))
p1 = People('dashu')#初始化 调用__init__方法,__init__不能有return值 但是可以return None
print(p1.country)


country = 'CA'
class People:
    def __init__(self, name):
        self.name = name
        print(country)
    def play_ball(self, ball):
        print('%s正在玩%s'%(self.name,ball))
p1=People('大树')


# #CA -->通过点调用即为类属性或者实例属性 不是通过点调用的即与类属性实例属性无关,不会从类里面找 即找最外面的
country = 'CA'
class People:
    country='JP'
    def __init__(self, name):
        self.name = name
        print(country)
    def play_ball(self, ball):
        print('%s正在玩%s'%(self.name,ball))
p1=People('大树')

# ----------------------
class People:
    country = 'Ch'
    l=['a','b']
    def __init__(self,name):
        self.name=name
    def eat_food(self,food):
        print('%s正在吃%s'%(self.name,food))
p1=People('大树')
print(p1.l)#['a', 'b']
# p1.l=[1,2,3]#实例对象的l 不是类的l
# print(People.l)#['a', 'b']
# print(p1.__dict__)
p1.l.append('c')
print(p1.__dict__)
print(p1.l)
print(People.l)
对象的调用
原文地址:https://www.cnblogs.com/gl-gl/p/9204216.html