1.用函数模拟类的创建
#用函数模拟类的创建
def chinese(name,age):
def ini():
dic = {
'name':name,
'age':age,
'eat':eat,
'sleep':sleep
}
return dic
def eat(food):
print('正在吃%s'%(food))
def sleep():
print('正在睡觉')
return ini()
print(chinese('alex','18')['eat']('土'))
2.类的创建
class chinese:
country = 'China'
def __init__(self,name,age):
self.name = name
self.age = age
def eat(self,food):
print('%s正在吃%s'%(self.name,food))
def sleep(self):
print('正在睡觉')
p1 = chinese('alex','18')
print(p1.name)
p1.eat('土')
3.类属性的删增改查/类方法的增改
class chinese:
country = 'China'
def __init__(self,name,age):
self.name = name
self.age = age
def eat(self,food):
print('%s正在吃%s'%(self.name,food))
def sleep(self):
print('正在睡觉')
p1 = chinese('alex','18')
print(p1.name)
p1.eat('土')
#查看类属性
print(chinese.country)
#修改类属性
chinese.country = 'America'
print(chinese.country)
#删除类属性
del chinese.country
print(chinese.__dict__)
#增加类属性
chinese.country = 'China'
chinese.location = 'Asia'
print(dir(chinese))
#类方法的增加
def working():
print('正在工作')
chinese.working = working
chinese.working()
#修改类方法
def test():
print('测试')
chinese.eat = test
chinese.eat()
4.通过实例修改属性只修改了实例的
#通过实例修改属性只修改实例的
class Chinese:
country = 'China'
def __init__(self,name):
self.name = name
def play_ball(self,ball):
print('%s正在打%s'%(self.name,ball))
p1 = Chinese('alex')
print(p1.country)
p1.country = '日本'
print('类的--->',Chinese.country)
print('实例的-->',p1.country)