
正文
python面向对象--类和实例的认识
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
'''1.数据属性 2.函数属性''' #创建一个类
class Chinese:
"这是一个中国人的类" #类属性
money=4000
#注意类和对象均用点来访问自己的属性
def __init__(self,name,age,grender):
self.mingzi=name
self.nianji=age
self.xingbie=grender def tu():
print("随地吐痰") def cha_dui(self):
print("%s 插队到前面"%self.mingzi) def eat_food(self,food):
print("%s 正在吃 %s" % (self.mingzi,food)) #实例属性
p1=Chinese("元昊",18,"boy") print(p1.__dict__)#对象数据属性 --实例只有数据属性 print(p1.mingzi)
print(p1.__dict__['xingbie']) Chinese.cha_dui(p1)
print(Chinese.__dict__) p1.team="zhongguo"
print(p1.team) print(dir(p1))
p1.cha_dui()
print(p1.eat_food("饭"))
print(p1.money) #实例一定能访问类属性,类属性访问不了实例属性 # print(Chinese)
# print(Chinese.money)
# Chinese.tu()
# Chinese.cha_dui('元昊') #查看类的属性
#print(dir(Chinese)) #查看类的属性字典
# print(Chinese.__dict__['money'])
# Chinese.__dict__['cha_dui']('yuanhao') # print(Chinese.__name__)
# print(Chinese.__doc__)
# print(Chinese.__bases__)
# print(Chinese.__class__) #实例化对象
# p1=Chinese()
#
# print(p1) # def test():
# pass
#
#
# print(test)
#类属性的增删查改
class Chinese:
#类属性
country="China" def __init__(self,name):
self.name=name def play_basketball(self,ball):
print("%s 正在打 %s" %(self.name,ball)) #查看
print(Chinese.country) #修改
Chinese.country="Japan" print(Chinese.country) p1=Chinese("alex")
print(p1.__dict__)
print(p1.country) #增加
Chinese.resname="XXXX"
print(Chinese.resname)
print(p1.resname) #删除类的属性
del Chinese.resname
print(Chinese.__dict__) #类的属性函数添加
def eat_food(self,food):
print("%s xxxxx%s" %(self.name,food)) Chinese.eat=eat_food print(Chinese.__dict__)
p1.eat("肉") def test(self):
print("test") Chinese.play_ball=test
#Chinese.play_ball("sss")
p1.play_ball()
#实例属性的增删查改
class Chinese:
#类属性
country="China" def __init__(self,name):
self.name=name def play_basketball(self,ball):
print("%s 正在打 %s" %(self.name,ball)) p1=Chinese("alex") #查看
print(p1.__dict__)
print(p1.name)
p1.play_basketball("篮球") #增加数据属性
p1.age=18
print(p1.__dict__)
print(p1.age) #不要修改底层的属性字典
# p1.__dict__['sex']="maile"
# print(p1.__dict__) #修改
p1.age=19
print(p1.__dict__) #删除
del p1.age
print(p1.__dict__) #定义一个类,只当一个作用域去用
class Mydate:
pass
x=10
y=20
Mydate.x=2
Mydate.y=8
print(x,y)
print(Mydate.x,Mydate.y)







