面相对象和时间模块
1.属性:用数据来描述类的信息
方法:用函数来描述类的信息
1.1)属性 — 类属性、对象属性(属性的本质就是变量)
类属性
a.怎么定义:直接定义在类中的变量就是类属性
b.怎么使用:用‘类.'的方式来使用
c.什么时候用:属性不会因为对象不同而不一样的时候使用
1.2)对象属性
a.怎么定义:以‘self.属性名=值’的形式定义在_ _ini _ _方法中
b.怎么使用: 用‘对象.’的方式来使用
c.什么时候使用:属性会因为对象不同而不一样的时候使用
class Person:
"""人类"""
# 类属性: a、x
a = 10
x = 'abc'
# 对象属性:name、age、gender
def __init__(self):
self.name = '小明'
self.age = 18
self.gender = '男'
# 使用类属性
print(Person.a)
print(Person.x)
Person.a = 100
print(Person.a)
# 使用对象属性
p = Person()
print(p.name)
print(p.age, p.gender)
p.name = '小花'
print(p.name)
class Circle:
"""圆"""
pi = 3.1415926
def __init__(self):
self.r = 0
print(Circle.pi)
# 练习:定义一个矩形类,有属性:宽度、高度、角的个数
class Rect:
corner_count = 4
def __init__(self):
self.width = 0
self.height = 0
2.对象属性初始值
方法一:赋一个固定的值
方法二:使用没有默认值的参数
方法三:使用有默认值的参数
class Student:
def __init__(self, name, gender='男'):
self.name = name
self.is_adult = True
self.gender = gender
stu1 = Student('张三')
# stu1.name = '张三'
print(stu1.name)
stu2 = Student('李四')
# stu2.name = '李四'
print(stu2.name)
stu2.is_adult = False
stu3 = Student('小花', '女')
print(stu3.name, stu3.gender)
# 练习:定义圆类,有属性:半径和圆心。要求创建对象的时候半径必须赋值,圆心可以赋值也可以不赋值,如果没有圆心在坐标原点
class Circle:
"""圆"""
def __init__(self, r, center=(0, 0)):
self.r = r
self.center = center
c1 = Circle(10, (10, 20))
c2 = Circle(10)
3.方法
3.1)方法:对象方法、类方法、静态方法
对象方法
怎么定义:直接定义在类中的函数
怎么调用:对象.
特点:有个默认参数self,用对象调用的时候不用传参,谁调用就指向谁(self—当前对象)
什么时候使用:实现函数的功能需要对象就使用对象方法
3.2)类方法
怎么定义:在定义函数前加@classmethod
怎么调用:类
特点:有个默认参数cls,调用的使用不用传参,指向当前类
什么时候:不需要对象的时候,实现函数的功能需要类
3.3)静态方法
怎么定义:在定义函数前加@staticmethod
怎么调用:类
特点:没有默认参数
什么时候使用:实现函数的功能既不需要对象也不需要类
class A:
def func1(self):
print(f'对象方法: {self}')
@classmethod
def func2(cls):
print(f'cls:{cls}')
print('类方法')
@staticmethod
def func3():
print('静态方法')
a = A()
a.func1()
print(f'a:{a}')
A.func2()
print(f'A:{A}')
A.func3()
class Circle:
"""圆"""
pi = 3.1415926
def __init__(self, r):
self.r = r
# 计算圆的面积
def area(self):
# 对象方法中如果需要对象属性,用self来提供
return Circle.pi * self.r ** 2
c1 = Circle(1)
c2 = Circle(2)
print(c1.area())
print(c2.area())
c1.r = 10
print(c1.area())
# 练习:定义一个纸牌类,属性:花色和数值 方法:显示扑克
class Poker:
"""扑克类"""
def __init__(self, color, num):
self.color = color
self.num = num
def show(self):
print(f'{self.color}{self.num}')
# 打印当前类的对象的时候,打印__repr__的返回值(返回值必须是字符串)
def __repr__(self):
# self - 打印谁,self就指向谁
# return f'{self.color}{self.num}'
return f'color-{self.color}, num-{self.num}'
# return f'<{__name__}.{type(self).__name__} objct at {id(self)}>'
p1 = Poker('♥', 'A')
p2 = Poker('♣', '10')
p1.show()
p2.show()
print(f'p1:{p1}')
print(f'p2:{p2}')
4.对象属性的增删改查
# 1.字典
stu1 = {'name': '小明', 'age': 18, 'gender': '男'}
stu2 = {'name': '小花', 'age': 20, 'gender': '女'}
print(stu1['name'])
stu1['score'] = 90
stu1['name'] = '张三'
del stu1['age']
# 2.对象
class Student:
"""学生类"""
def __init__(self, name, age, gender='男'):
self.name = name
self.age = age
self.gender = gender
self.math = 89
self.chinese = 90
self.English = 45
def get_mean_score(self):
"""获取平均分"""
return (self.math + self.chinese + self.English) / 3
stu1 = Student('小明', 18)
stu2 = Student('小花', 20, '女')
stu2.English = 60
# 获取对象元素的值
print(stu1.name)
# 添加对象属性
stu1.score = 90
print(stu1.score)
# 修改对象属性
stu1.name = '张三'
print(stu1.name)
# 删除对象属性
# del stu1.age
# print(stu1.age)
print(stu1.get_mean_score())
print(stu2.get_mean_score())
5.继承
继承就是让子类直接拥有父类的属性和方法。
子类 — 继承者
父类 — 被继承者
5.1怎么创建继承关系
class 类名(父类)
类的说明文档
类的内容
class 类名: == class 类名(object):
object — Python的基类
class Person:
def __init__(self):
self.name = '小明'
self.age = 18
self.gender = '男'
class Student(Person):
pass
stu = Student()
print(stu.name, stu.age, stu.gender)
5.2继承的时候:子类继承父类所有的属性和方法
class A:
a = 100
def __init__(self):
self.b = 200
def func1(self):
print('对象方法')
@classmethod
def func2(cls):
print('类方法')
@staticmethod
def func3():
print('静态方法')
class B(A):
pass
print(B.a)
obj = B()
print(obj.b)
obj.func1()
B.func2()
B.func3()
5.3子类添加内容
1)添加类属性和方法
直接在子类中定义新的
2)添加对象属性
需要在子类的_ _init _ 方法中通过super去调用父类的 _init _ _方法
类中方法的调用:
先看当前类中有没有对应的方法,如果有直接调用,没有就看父类中有没有,父类没有就找父类的父类,以此类推,如果找到object都找不到才报错
class C:
a = 100
def func1(self):
print('C中的对象方法')
class D(C):
b = 200
def func2(self):
print('D中的对象方法')
print(D.a, D.b)
obj = D()
obj.func1()
obj.func2()
class Person:
def __init__(self, name):
self.name = name
self.age = 18
self.gender = '男'
class Student(Person):
"""学生类"""
def __init__(self, name):
# 调用父类的__init__
super(Student, self).__init__(name)
self.subject = 'Python'
self.study_id = 'Py001'
pass
stu = Student('小明')
print(stu.name, stu.age, stu.gender)
print(stu.subject, stu.study_id)
6.time模块
6.1time()— 获取当前时间(返回的是时间戳)
时间戳:用时间差来表示时间(距离1970年1月1日0时0分(格林威治)的时间差,单位是秒)
t1 = time.time()
print(t1) # 1635493955.7802172 (2021年10月29日 15:52:35)
6.2 localtime
localtime () — 获取当前时间的本地时间(返回结构体时间)
localtime(时间戳) — 将时间戳转换成本地时间对应的结构体时间
t2 = time.localtime()
print(t2)
print(t2.tm_year,t2.tm_mon)
t3 = time.localtime(0)
print(t3)
t4 = time.localtime(1635493955.7802172)
print(t4)
6.3结构体时间和字符串的相关转换
strftime(时间格式,结构体时间) — 将指定时间以指定的格式转换成字符串
strptime(字符串时间值,时间格式) — 将字符串时间转换成结构体时间
t2 = time.localtime()
t2_str = f'{t2.tm_year}年{t2.tm_mon}月{t2.tm_mday}日 {t2.tm_hour}:{t2.tm_min}:{t2.tm_sec:0>2}'
print(t2_str) # '2021年10月29日 16:34:4'
# XXXX年xx月xx日 xx:xx:xx
t2_str = time.strftime('%Y年%m月%d日 %H:%M:%S', t2)
print(t2_str) # '2021年10月29日 16:36:04'
# XXXX-xx-xx xx:xx:xx
t2_str = time.strftime('%Y-%m-%d %H:%M:%S', t2)
print(t2_str)
# xx月xx日 星期几
t2_str = time.strftime('%B %A', t2)
print(t2_str)
# 上午/下午 xx:xx
t2_str = time.strftime('%p %I:%M', t2)
print(t2_str)
t3_str = '2012/3/17'
t3 = time.strptime(t3_str, '%Y/%m/%d')
print(t3)
t3_str = '2013年3月17日'
t3 = time.strptime(t3_str, '%Y年%m月%d日')
print(t3)
# 解决时间格式中有中文报错的问题
# import locale
# locale.setlocale(locale.LC_CTYPE, 'chinese')
6.4将结构体时间转换成时间戳
t4 = time.mktime(t3)
print(t4) # 1363449600.0
6.5 sleep
sleep(时间) — 让程序暂停(睡眠)指定时间,单位:s
time.sleep(3)
print('=======================')
课后作业
# 1.定义一个狗类和一个人类:
# 狗拥有属性:姓名、性别和品种 拥有方法:叫唤
# 人类拥有属性:姓名、年龄、狗 拥有方法:遛狗
class Dog:
"""狗类"""
@ classmethod
def func1(cls):
print('叫唤')
def __init__(self, name, gender, variety):
self.name = name
self.gender = gender
self.variety = variety
class Person():
"""人类"""
def __init__(self, name, age, dog):
self.name = name
self.age = age
self.dog = dog
print('遛狗')
# 2.定义一个矩形类,拥有属性:长、宽 拥有方法:求周长、求面积
class Square:
"""矩形"""
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
def perimeter(self):
return (self.length + self.width) * 2
square1 = Square(5, 6)
print(square1.area())
print(square1.perimeter())
# 3.定义一个二维点类,拥有属性:x坐标、y坐标 拥有方法:求当前点到另外一个点的距离
class Point:
"""二维坐标点"""
def __init__(self, x1, y1, x2, y2):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
def distance(self):
return ((self.x1 - self.x2)**2 + (self.y1 - self.y2)**2)**0.5
point1 = Point(20, 10, 8, -2)
print(point1.distance())
# 4.定义一个圆类,拥有属性:半径、圆心 拥有方法:求圆的周长和面积、判断当前圆和另一个圆是否外切
class Circle:
"""圆"""
pi = 3.1415926
def __init__(self, r, center=(0,0)):
self.r = r
self.center = center
def perimeter(self):
return Circle.pi * self.r * 2
def area(self):
return (Circle.pi * self.r)**2
def inscirbed_circle(self, a):
return (self.r + a.r) == ((self.center[0] - a.center[0])**2 + (self.center[1] - a.center[1]**2))**0.5
circle1 = Circle(5, (10, 6))
circle2 = Circle(3, (6, 3))
print(circle1.inscirbed_circle(circle2))
# 5.定义一个线段类,拥有属性:起点和终点, 拥有方法:获取线段的长度
class Line:
"""线段"""
def __init__(self, start:Point, end:Point):
self.start = start
self.end = end
def length(self):
return ((self.start[0] - self.end[0])**2 + (self.start[1] - self.end[1])**2)**0.5
t1 = Line((10, 8), (20, 5))
print(t1.length())