?实例-体现面向对象
以面向对象的角度,编写一个程序。判断学生是否完成作业,如果完成就表扬,否则进行批评
class Student:
def __init__(self,name,grade,subject):
self.name = name
self.grade = grade
self.subject = subject
def do_homework(self,time):
if self.grade > 3 and time >2:
return True
elif self.grade <3 and time <0.5:
return True
else:
return False
class Teacher:
def __init__(self,name,subject):
self.name = name
self.subject = subject
def evalute(self,result=True):
if result:
return 'you R great'
else:
return 'you should work hard'
stu_zhangsan = Student('zhangsan',5,'math')
teacher_wang = Teacher('wang','math')
teacher_said = teacher_wang.evalute(stu_zhangsan.do_homework(1))
print('teacher {0} said:{1},{2}'.format(teacher_wang.name,stu_zhangsan.name,teacher_said))
stu_newton = Student('newton',6,'physics')
teacher_newton_said = teacher_wang.evalute(stu_newton.do_homework(4))
print('teacher {0} said:{1},{2}'.format(teacher_wang.name,stu_newton.name,teacher_newton_said))
实例-体现self
创建一个类,能计算任意两个日期之间的天数
import datetime
from dateutil import rrule
class BetDate:
def __init__(self,start_date,stop_date):
self.start = datetime.datetime.strptime(start_date,'%Y,%m,%d')
self.stop = datetime.datetime.strptime(stop_date,'%Y,%m,%d')
def days(self):
d = self.stop - self.start
return d.days if d.days>0 else False
def weeks(self):
weeks = rrule.rrule(rrule.WEEKLY,dtstart=self.start,until=self.stop)
return weeks.count()
fir_twe = BetDate("2019,5,1","2019,11,25")
d = fir_twe.days()
w = fir_twe.weeks()
print(d)
print(w)
?实例-体现静态方法、类方法
实例:创建类 通过‘年-月-日’字符串创建实例,并检验年月日是否合法
与实例无关就可以写成静态方法。
class Date(object):
def __init__(self,year=0,month=0,day=0):
self.year = year
self.month = month
self.day = day
@classmethod
def from_string(cls,date_as_string):
year,month,day=map(int,date_as_string.split('-'))
date1 = cls(year,month,day)
return date1
@staticmethod
def is_date_valid(date_as_string):
year,month,day=map(int,date_as_string.split('-'))
return day<=31 and month<=12 and year<=2038
d = Date.from_string('2019-11-11')
is_date = Date.is_date_valid('2019-11-11')
print(d)
print(is_date)
类的特性?
继承
?
|