类和方法
面向对象编程的特性:
- 程序包括类的定义和方法定义;
- 大部分的计算通过对于对象进行操作;
- 对象对应于某些概念,方法对应于对该对象的交互
方法:在类中定义的函数,方法的第一个形参通常是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)