4.如何在类外,给对象动态添加绑定方法
import types
def qingtianzhu(obj,name):
print("请我叫我一柱擎天,简称{},颜色是{}".format(name,obj.color))
obj.qingtianzhu = types.MethodType(qingtianzhu,obj)
obj.qingtianzhu("擎天柱")
8.菱形继承中,如何查看多继承调用顺序关系
12.写一个能体现多态的案例
class Soldier():
def attack(self):
pass
def back(self):
pass
# 陆军
class Army(Soldier):
def attack(self):
print("[陆军]搏击,ufc,无限制格斗,太极,八卦,占星,制作八卦符")
def back(self):
print("[陆军]白天晨跑10公里,也行800百公里")
# 海军
class Navy(Soldier):
def attack(self):
print("[海军]潜泳水下30个小时,手捧鱼雷,亲自送到敌人的老挝,炸掉敌人的碉堡")
def back(self):
print("[海军]每小时在海底夜行800公里,游的比鲨鱼还快")
# 空军
class AirForce(Soldier):
def attack(self):
print("[空军]空中夺导弹,手撕飞机,在空中打飞机,精准弹幕")
def back(self):
print("[空军]高中跳伞,落地成盒")
army_obj = Army()
navy_obj = Navy()
af_obj = AirForce()
lst = [army_obj,navy_obj,af_obj] # 对象列表
strvar = """
1.所有兵种开始攻击训练
2.所有兵种开始撤退训练
3.空军练习攻击,其他兵种练习撤退
"""
print(strvar)
num = input("将军请下令,选择训练的种类")
for i in lst:
if num == "1":
i.attack()
elif num == "2":
i.back()
elif num == "3":
if isinstance(i,AirForce):
i.attack()
else:
i.back()
else:
print("将军~ 风太大 我听不见~")
break
19.模拟int强转整型操作,实现相应方法
import math
class MyInt():
def calc(self,num,sign=1):
strvar = num.lstrip("0")
if strvar == "":
return 0
return eval(strvar) * sign
def __call__(self,num):
if isinstance(num , bool):
if num == True:
return 1
elif num == False:
return 0
elif isinstance(num,int):
return num
elif isinstance(num,float):
# 方法二
"""
if num >= 0:
return math.floor(num)
else:
return math.ceil(num)
"""
return math.floor(num) if num >= 0 else math.ceil(num)
elif isinstance(num,str):
if (num[0] == "+" or num[0]== "-") and num[1:].isdecimal():
if num[0] == "+":
sign = 1
else:
sign = -1
return self.calc(num[1:],sign)
elif num.isdecimal():
return self.calc(num)
else:
return "老铁,这个真转不了"
myint = MyInt()
res = myint(True)
print(res)
res = myint(100)
print(res)
res = myint(3333.14)
print(res, type(res))
20.计算类中自定义成员个数
class MyClass():
pty1 = 1
pty2 = 2
__pty3 = 3
pyt3 =10
pty100 = 90
def func1():
pass
def __func2():
pass
def __func3():
pass
def __len__(self):
lst = []
dic = MyClass.__dict__ # 遍历类中所有成员
for i in dic: # 遍历类中所有成员
if not(i.startswith("__") and i.endswith("__")): # 如果开头和结尾都不是以双下划线结尾
lst.append(i) # 将符合条件的成员添加到列表中
return len(lst)
23.获取当前类继承的父类