提问者:小点点

允许一个子类有不同的args和kwargs从它的父类在python


下面的代码是一个基本的Angle对象的初始化方法,它的父类是浮动。

class Angle(float):
    def __init__(self, value, vertex2 = None, vertex3 = None, atype = 'convex'):

        #type-checking for the input args
        try:
            #checks for value arg
            angle = value
            if not (0 < value < 360):
                angle %= 360
        except TypeError:
            #checks for three-vertice args
            try:
                angle = three_point_angle(value, vertex2, vertex3)
                #three_point_angle is a function to calculate the
                #convex angle between three vertices (i.e. at vertex2)
                if atype == 'concave':
                    angle = 360 - angle
                self._vdict = {}
                for pos, vert in enumerate([value, vertex2, vertex3]):
                    self._vdict[pos] = vert
            except:
                raise TypeError(\
                    "You may only specify either an angle value, or three vertices from which \
                    to calculate the angle. You input a %s, %s and %s value." % (\
                        type(value), type(vertex2), type(vertex3)))
        self.angle = angle

此类背后的思想是,您可以输入角度值,或者指定三个顶点(以及可选的角度类型参数)以自动计算角度。最后,自我。角度总是初始化的,这是进行所有运算的地方(因此\uuuu add\uuuu(self,other)会影响self。角度)。

它从float继承的原因是继承了反射和增强赋值的神奇方法,这些方法都是在self上执行的。角度

当试图为顶点输入三个值时,就会出现问题。由于它继承自float,因此不能接受多个参数,因此会引发错误。我该如何解决这个问题?我的猜测是,我必须为Angle创建一个\uuuuuuu新的方法,这样它将被调用,而不是超类',但我甚至不知道从哪里开始,或者这是否是正确/最好的方法。


共2个答案

匿名用户

您不需要从float继承。你认为神奇的方法是在自己身上实施的,这是错误的。角他们只是自我表演。请尝试以下代码:

class Angle(float):
    def __init__(self, x):
         self.angle = x
    def double(self):
         self.angle *= 2
a = Angle(1)
a.double()
print a # prints 1.0
print a.angle # prints 2
a *= 5
print a # prints 5.0
print a.angle # throws AttributeError

a.angle不受魔法方法的影响,float(a)也不受a.angle上的操作的影响floats是不可变的,因此a*=5创建了一个具有不同属性的新float。

因此,如果将角度更改为继承自对象而不是浮动,则可以控制初始化,而不会失去任何便利。

匿名用户

见这一相关问题:

如何在Python中为自定义类重载'float()'?

然后改变

class Angle(float):

class Angle(object):