复习
"""封装"""
class Lx(object):
def __init__(self, name, age):
self.__name = name
self.__age = age
def shown(self):
print(self.__name, self.__age)
def __str__(self):
return '{},{}'.format(self.__name, self.__age)
t = Lx('胡丽琴', 90)
t.shown()
# print(t.__age)
print(t)
"""继承"""
class Ball(object):
def __init__(self, zhonglei, jiage):
self.zhonglei = zhonglei
self.jiage = jiage
class Basketball(Ball):
def __init__(self, zhonglei, jiage, renshu):
super().__init__(zhonglei, jiage)
self.renshu = renshu
def shown(self):
print(self.zhonglei, self.jiage, self.renshu)
t = Basketball('篮球', 14, 19)
t.shown()
"""多态"""
from random import *
class A(object):
def xx(self):
print("1")
class B(object):
def xx(self):
print("2")
class C(object):
def xx(self):
print("3")
def yy(y):
y.xx()
i = randint(0, 2) # 根据列表a的长度随机获得一个下标索引
a = [A, B, C] # 将类名放置在列表a内
t = a[i]() # 对象t随机进行一个类的实例化
yy(t) # 将实例化对象t传递至函数yy
Python中的魔法函数
在满足条件时会自动执行的函数
class Fantisy():
def __new__(cls, *args, **kwargs): #用于对象实例化,在对象实例化时总是第一个执行。
print('new执行')
return object.__new__(cls) #不可缺少,如果不执行返回该值的操作,后面的魔法函数将无法执行
def __init__(self, num): #用于对象属性初始化,总在对象实例化后执行,即总是第二个执行
print('init执行')
self.num = num
def __call__(self, x):#用于被调用时执行
return 'call执行'
def __hash__(self):#用于执行哈希加密时执行
print('hash执行')
return hash(self.num)#哈希函数必须返回并且只能哈希类型,否则会报错
def __eq__(self, other):#当执行等值判断时执行
return 'eq执行' #当使用eq时如果设置了返回值则返回设置的值,否则返回none
def __str__(self): #执行字符化时执行,如print,%s等
return 'str执行' #返回字符串化的值
def __repr__(self): #如果没有str函数,则执行repr
print('repr执行')
def __del__(self): #当执行删除操作或者是整个对象实例化完成后并且整个程序结束时自动执行
print('del执行')
a = Fantisy(8)
b = Fantisy(10)
print(a(43))
# b = Fantisy
# print(b(12))
print(hash(a))
print(a)
print(a == b)
#执行结果
new执行
init执行
new执行
init执行
call执行
hash执行
8
str执行
eq执行
del执行
del执行
hasattr
class Stu(object):
count = 0
def __init__(self, name):
self.name = name
a = Stu('西瓜')
b = hasattr(a, 'name')
c = hasattr(a, '__init__')
d = hasattr(a, 'age')
print(b, c, d)
a.age = 10
d = hasattr(a, 'age')
print(d)
if not hasattr(a, 'age'):
print("没有age")
if hasattr(a, 'age'):
print('有')
if not hasattr(Stu, 'countT'):
print('没有')
Stu.countT = 12345
print(Stu.countT)
单例模式
"""单例模式"""
class A(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, 'inst'):
cls.inst = object.__new__(cls)
return cls.inst
def __init__(self, name):
self.name = name
a = A('张三')
b = A('李四')
print(a == b)
print(a is b)
print(a.name)
print(b.name)
class B(object):
def __new__(cls, *args, **kwargs):
cls.inst = object.__new__(cls)
return cls.inst
def __init__(self, name):
self.name = name
a1 = B('张三')
b1 = B('李四')
print(a1 == b1)
print(a1 is b1)
print(a1.name)
print(b1.name)
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)
print(a is b)
print(id(a), id(b))
class A(object):
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
if self.name == other.name and self.age == other.age:
print("正判断:", end='')
return True
else:
return False
a = A('张三', 19)
b = A('李四', 19)
c = A('张三', 19)
print(a == b)
print(a == c)
print(id(a))
print(id(c))
listA=[]
if a not in listA:
listA.append(a)
if b not in listA:
listA.append(b)
if c not in listA:
listA.append(c)
print(listA)
for i in listA:
print(i)
a = [1, 2, 3]
b = [1, 2, 3]
c = []
"""not的布尔判断只进行值的比较,不做内存地址的比较"""
if a not in c:
c.append(a)
if b not in c:
c.append(b)
print(c)
class B(object):
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
print(self.__dict__)
return self.__dict__ == other.__dict__
a2 = B('张三', 19)
b2 = B('李四', 19)
c2 = B('张三', 19)
print(a2 == b2)
print(a2 == c2)
print(b2 == a2)
print(id(a2))
print(id(c2))
class A():
dic = {"查看教师信息": "fun1", "查看学生信息": "fun2"}
def fun1(self):
print('教师信息')
def fun2(self):
print('学生信息')
a = A()
df = input('请输入')
if hasattr(a, a.dic.get(df)):
s = getattr(a, a.dic[df])
s()
else:
print('无此功能')
getattr
class Teacher():
d = {1, 2, 3, '4'}
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def fun1(cls):
print('111')
def fun2(self):
print('222')
a = Teacher('张三', 24)
b = Teacher('李四', 45)
d = getattr(Teacher, 'd') # 从类中获取属性
print(d)
c = getattr(a, 'age') # 从对象中获取属性
print(c)
c = getattr(b, 'name')
print(c)
e = getattr(Teacher, 'fun1')
print(e)
e()
f = getattr(a, 'fun2')
f()
作业(1)
"""通过类进行文件读取"""
class Write(object):
def __init__(self, fileName):
self.fileName = fileName
def fileName_open(self):
self.a_write = open(self.fileName, 'w')
def fileName_write(self):
wrtie_str = input("请输入添加内容")
self.a_write.write(wrtie_str)
def fileName_close(self):
self.a_write.close()
class Read():
def __init__(self, fileName):
self.fileName = fileName
def fileName_openread(self):
self.a_read = open(self.fileName, 'r')
def fileName_read(self):
allother = self.a_read.read()
print(allother)
def fileName_close(self):
self.a_read.close()
w = Write('a.txt')
w.fileName_open()
w.fileName_write()
w.fileName_close()
r = Read('a.txt')
r.fileName_openread()
r.fileName_read()
r.fileName_close()
作业(2)
"""魔法方法__eq__"""
from random import *
class Change(object):
def __init__(self, num):
self.num = ord(num)
def __eq__(self, other):
if self.num % 3 == 0 and other.num % 3 == 0:
print(self.num, other.num)
return True
else:
print(other.num,chr(other.num))
return False
c = False
while c != True:
A = chr(randint(65, 90))
B = chr(randint(65, 90))
a = Change(A)
b = Change(B)
c = a == b
print(c)
作业(3)
""" 魔术方法 __hash__ 和 __eq__练习
设计二维坐标类Point,比较2个坐标到原点的距离是否相等?"""
from math import *
class Point():
def __init__(self, x, y):
self.x = x
self.y = y
def __hash__(self):
return hash((self.x, self.y))
def __eq__(self, other):
if sqrt(self.x ** 2 + self.y ** 2) == sqrt(other.x ** 2 + other.y ** 2):
print('距离相等')
return True
else:
print('距离不相等')
return False
p1 = Point(-5, 7)
p2 = Point(5, 7)
print(hash(p1))
print(hash(p2))
print(p1 is p2)
print(p1 == p2)