题目
2、通过定义元类来实现以其作为元类的的类具有主人(onwer)类属性
3、为前面课程中的色子类定义方法实现:色子可以迭代、可比较,可进行加、减运算。
答案
2、
class MyMeta(type):
def __init__(self, name, bases, dicts):
pass
def __new__(cls, name, bases, dicts):
res = type.__new__(cls, name, bases, dicts)
res.owner = "Zhang San" #主人属性
return res
class custom(metaclass=MyMeta):
pass
3、
class Dice:
def __init__(self, num, start=1, end=6,):
self.start = start
self.end = end
self.num = num
def __iter__(self):
return self
def __next__(self):
if self.num < self.end:
r = self.num
self.num += 1
return r
else:
raise StopIteration
def __lt__(self, other):
return self.num < other.num
def __gt__(self, other):
return self.num > other.num
def __eq__(self, other):
return self.num == other.num
def __add__(self, other):
return Dice(num=self.num + other.num)
def __sub__(self, other):
return Dice(num=self.num - other.num)
测试
2、
if __name__ == "__main__":
cus = custom()
print(cus.owner) # Zhang San
3、
if __name__ == "__main__":
import random
a = Dice(num=1)
print(a.num) # 1
for i in a:
print(i, ",", end="") # 1,2,3,4,5,6
b = Dice(num=3)
print(b.num) # 3
print(a < b) # False
print(a > b) # True
print(a == b) # False
c = a + b
print(c.num) # 9
d= b - a
print(d.num) # -3