python基础类(2021/08/09)

 实例-体现面向对象

以面向对象的角度,编写一个程序。判断学生是否完成作业,如果完成就表扬,否则进行批评

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
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值