类的初始化,方法及特殊方法

类和方法

面向对象编程的特性:

  • 程序包括类的定义和方法定义;
  • 大部分的计算通过对于对象进行操作;
  • 对象对应于某些概念,方法对应于对该对象的交互

方法:在类中定义的函数,方法的第一个形参通常是self

特殊方法

__init__():特殊方法,当对象被初始化时就会被调用,形参和类的属性名称通常相同;

__str__():打印对象时调用并输出

__add__()重载操作符,能够在Time类上使用+

isinstance(other, class) :内置函数,判断实例是否属于某个类

一般写对象的时候先写__init__()__str__()函数,便于初始化和调试。

虽然在程序运行中都可以在对象中添加属性,但是为了不容易出现错误,通常需要在__init__方法中初始化全部属性


定义一个Time类,要求:

  • 包括属性hour, minute, second

  • 包括方法print_time,调用该方法实现打印时间hour:minute:second

  • 重载操作符__add__(),实现对于两个类的相加

class Time:
    def __init__(self, hour, minute, second):
        self.hour = hour
        self.minute = minute
        self.second = second
        
    def int_to_time(self,n):
        h = n//3600
        h = h%24
        n = n%3600
        m = n//60
        s = n%60
        return Time(h,m,s)
          
    def  time_to_int(self):
        return self.hour * 3600 + self.minute * 60 + self.second
    def __str__(self) :
        return "Time is : " + str(self.hour) + ":" + str(self.minute) + ":" + str(self.second)
    def __add__(self, other):
        seconds = self.time_to_int()+ other.time_to_int()
        return self.int_to_time(seconds)
    

    def  print_time(self):
        print(f"{self.hour}:{self.minute}:{self.second}")
time1 = Time(12, 30, 45)
time1.print_time()
time2 = Time(11,20,30)
print(time1 + time2)
print(time1)

输出:

12:30:45
Time is : 23:51:15
Time is : 12:30:45

Time类重载+,实现两个类的相加及类+整数功能。

class Time:
    def __init__(self, hour, minute, second):
        self.hour = hour
        self.minute = minute
        self.second = second
        
    def int_to_time(self,n):
        h = n//3600
        h = h%24
        n = n%3600
        m = n//60
        s = n%60
        return Time(h,m,s)
          
    def  time_to_int(self):
        return self.hour * 3600 + self.minute * 60 + self.second
    def __str__(self) :
        return "Time is : " + str(self.hour) + ":" + str(self.minute) + ":" + str(self.second)
    def increment_time(self, seconds):
        seconds+=self.time_to_int() 
        return self.int_to_time(seconds)
    def __add__(self, other):
        if not isinstance(other, Time):
            return self.increment_time(self, other)
        seconds = self.time_to_int()+ other.time_to_int()
        return self.int_to_time(seconds)
    

    def  print_time(self):
        print(f"{self.hour}:{self.minute}:{self.second}")
time1 = Time(12, 30, 45)
time1.print_time()
time2 = Time(11,20,30)
print(time1 + time2)
print(time1)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值