類屬性:
#例項屬性:-------------類屬性的增刪改查------------
class
people:
country = '
china
'def
__init__
(self,name):
self.name=name
defeat_food(self,food):
print('
%s正在吃%s
'%(self.name,food))
defplay_ball(self,ball):
print('
%s正在玩%s
'%(self.name,ball))
defsay_word(self,word):
print('
%s正在說%s
'%(self.name,word))
##檢視類屬性
(people.country)
#例項化乙個物件
p1=people('
dashu')
p1.country
p1.eat_food('粽子
')p1.play_ball(
'lanqiu')
#修改類屬性
people.country='
china
(people.country)
#刪除類屬性
delpeople.country
print(people.country)#
報錯 因為country屬性已經被刪掉
#增加類屬性
people.country = '
china
'people.count='
100'
(people.count)
defplay_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
defeat_food(self,food):
print('
%s正在吃%s
'%(self.name,food))
p1 = people('
guoguo')
print(p1.__dict__)#
檢視例項屬性
(p1.name)
p1.eat_food('粽子
')#訪問類
#增加資料屬性
p1.age=18
print(p1.__dict__
(p1.age)
##不要修改底層的屬性結構:
#p1.__dict__['***']='female'
#print(p1.__dict__)
#print(p1.***)#修改
p1.age=99
print(p1.__dict__
(p1.age)#刪除
delp1.age
print(p1.__dict__)
#物件的呼叫----------------區分哪些是呼叫類實行和例項屬性 哪些不是-----------------
class
people:
country = 'ch'
def__init__
(self,name):
self.name=name
defeat_food(self,food):
print('
%s正在吃%s
'%(self.name,food))
p1=people('
dashu')
(p1.country)
p1.country='jp'
(people.country)
(p1.country)
#報錯 p1.age僅在類裡面找country 找不到則報錯
country = 'ca'
class
people:
def__init__
(self, name):
self.name =name
defeat_food(self, food):
print('
%s正在吃%s
' %(self.name, food))
p1 = people('
dashu
')#初始化 呼叫__init__方法,__init__不能有return值 但是可以return none
(p1.country)
country = 'ca'
class
people:
def__init__
(self, name):
self.name =name
(country)
defplay_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
(country)
defplay_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
defeat_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__)c'
)print(p1.__dict__
(p1.l)
print(people.l)
類屬性與例項屬性
給例項繫結屬性的方法是通過例項變數,或者通過self變數 class student object def init self,name self.name name s student bob s.score 90但是,如果student類本身需要繫結乙個屬性呢?可以直接在class中定義屬性,這...
類屬性與例項屬性
類屬性 類屬性的增刪改查 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 p...
類屬性 例項屬性
例項屬性 物件屬性 顧名思義,類屬性就是類物件所擁有的屬性,它被所有類物件的例項物件所共有,在記憶體中只存在乙個副本,這個和c 中類的靜態成員變數有點類似。對於公有的類屬性,在類外可以通過類物件和例項物件訪問 例項如下 class people object name tom 公有的類屬性 age ...