#面向对象
#需要有意义的面向对象的代码,不是有了类就是面向对象
#核心:类 对象
#实例化
#方法:设计层面 函数:程序运形,过程式一种称谓
class Student():
name = '' ##变量:数据成员
age = 0
def print_file(self):
print('name:' + self.name)
print('age:' + str(self.age))
student = Student()
student.print_file()
#对象:对象是现实世界或者思维世界中的实体在计算机中的反映,
#它将数据以及这些数据上的操作封装在一起
#类:一类事物的统称,对象是类具体化的产物,也就是实例化
#不同的对象有什么不同特点:比如年龄,姓名
class Student():
name = ''
age = 0
def do_homework(self):
print('homework')
student1 = Student()
student1.do_homework()
student2 = Student()
student2.do_homework()
student3 = Student()
student3.do_homework()
print(id(student1))
print(id(student2))
print(id(student3))
构造函数
class Student():
name = ''
age = 0
def __init__(self,name,age):
#构造函数
self.name = name
self.age = age
print('student')
# return 'student'
def do_homework(self):
print('homework')
student1 = Student('老李',38)
print(student1.name)
print(student1.age)
老李今年50岁,身高1.75,每天早上要跑步,会去吃东西
老吴今年36岁,身高1.85,老吴不跑步,老吴喜欢吃东西
class Person():
def __init__(self,name,age,height):
self.name = name
self.age = age
self.height = height
def __str__(self):
return '%s今年%s岁,身高%s'%(self.name,self.age,self.height)
def run(self):
if self.name == '老李':
return '%s爱跑步'%(self.name)
elif self.name == '老吴':
return '%s不跑步'%(self.name)
def eat(self):
return '%s吃东西'%self.name
laoli = Person('老李','50','1.75')
print(laoli)
print(laoli.run())
laowu = Person('老吴','36','1.85')
print(laowu)
print(laowu.eat())
str方法
class Dog():
def __init__(self,name):
self.name = name
def __str__(self):
#必须返回一个字符串
return '这是 %s' %(self.name)
Gofei = Dog('旺财')
print(Gofei)
回顾
class Cat():
def eat(self,name):
self.name = name
print('%s爱吃鱼'%self.name)
def drink(self):
print('猫要喝水