麦子学院——Python面向对象编程(P10类的特殊方法)

题目

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值