py17-面向对象
产生程序中的对象:
类名加括号,调用类,产生一个该类的实际存在的对象,该调用过程称为实例化,产生的结果又可以称为实例。
class OldboyStudent:
school = 'oldboy' #类的数据属性
def learn(self): #类的函数属性
print('is learning')
def eat(self):
print('is eating')
# print(OldboyStudent.__dict__['school'])
# print(OldboyStudent.__dict__['learn'])
# print(OldboyStudent.school)
# print(OldboyStudent.learn)
# OldboyStudent.x='xtyang'
# OldboyStudent.school='Oldboy'
# del OldboyStudent.school
# print(OldboyStudent.__dict__)
obj1=OldboyStudent()
obj2=OldboyStudent()
obj3=OldboyStudent()
print(obj1)
定义类:
class OldboyStudent:
school = 'oldboy' #类的数据属性
def __init__(self,name,age,sex): #在实例化时执行
self.name=name
self.age=age
self.sex=sex
def learn(self): #类的函数属性
print('is learning')
def eat(self):
print('is eating')
obj1=OldboyStudent('李大炮',18,'女')
#分两步
第一步:先产生空对象obj1
第二步:OldboyStudent.__init__(obj1,'李大炮',18,'女')
查看类的属性:
class OldboyStudent:
school = 'oldboy' #类的数据属性
def __init__(self,name,age,sex): #在实例化时执行
self.name=name
self.age=age
self.sex=sex
def learn(self): #类的函数属性
print('is learning')
def eat(self):
print('is eating')
obj1=OldboyStudent('李大炮',18,'女')
print(obj1.__dict__)
实际上:
class OldboyStudent:
school = 'oldboy' #类的数据属性
def __init__(self,name,age,sex): #在实例化时,产生对象之后执行
self.name=name
self.age=age
self.sex=sex
self.x=111111111111 #添加类的属性
# obj1.name='李大炮'
# obj1.age=18
# obj1.sex='女'
def learn(self): #类的函数属性
print('is learning')
def eat(self):
print('is eating')
obj1=OldboyStudent('李大炮',18,'女')
print(obj1.__dict__)
定义另外类:
class OldboyStudent:
school = 'oldboy' #类的数据属性
def __init__(self,name,age,sex): #在实例化时执行
self.name=name
self.age=age
self.sex=sex
# obj1.name='李大炮'
# obj1.age=18
# obj1.sex='女'
def learn(self): #类的函数属性
print('is learning')
def eat(self):
print('is eating')
obj1=OldboyStudent('李大炮',18,'女')
print(obj1.__dict__)
obj2=OldboyStudent('张全蛋',28,'男')
print(obj2.__dict__)
obj3=OldboyStudent('牛榴弹',18,'女')
print(obj3.__dict__)
对象的属性的修改:
class OldboyStudent:
school = 'oldboy' #类的数据属性
def __init__(self,name,age,sex): #在实例化时执行
self.name=name
self.age=age
self.sex=sex
# obj1.name='李大炮'
# obj1.age=18
# obj1.sex='女'
def learn(self): #类的函数属性
print('is learning')
def eat(self):
print('is eating')
obj1=OldboyStudent('李大炮',18,'女')
print(obj1.__dict__)
obj1.name='xtyang' #对象的属性的修改:
print(obj1.__dict__)
obj1.__dict__['name']='大炮' #字典格式的对象的属性的修改
print(obj1.name)
类就是一个字典,可以弹出
class OldboyStudent:
school = 'oldboy' #类的数据属性
def __init__(self,name,age,sex): #在实例化时执行
self.name=name
self.age=age
self.sex=sex
# obj1.name='李大炮'
# obj1.age=18
# obj1.sex='女'
def learn(self): #类的函数属性
print('is learning')
def eat(self):
print('is eating')
obj1=OldboyStudent('李大炮',18,'女')
print(obj1.__dict__)
obj1.name='xtyang'
print(obj1.__dict__)
obj1.__dict__['name']='大炮'
print(obj1.name)
obj1.__dict__.pop('name') #弹出
print(obj1.__dict__)