類屬性與實例屬性

類屬性:app

#-------------類屬性的增刪改查------------
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')

實例屬性:ide

# #--------------實例屬性增刪改查---------------
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)
對象的調用
相關文章
相關標籤/搜索