简体   繁体   English

在Python中定义方法别名?

[英]Define method aliases in Python?

I have a vector class and I defined the __mul__ method to multiply a vector by a number. 我有一个矢量类,我定义了__mul__方法将矢量乘以数字。

Here is the __mul__ method : 这是__mul__方法:

def __mul__(self, other):
    x = self.x * other
    y = self.y * other
    new = Vector()
    new.set_pos((x, y))
    return new

My problem is that I don't know which is which between the number and the vector. 我的问题是我不知道数字和矢量之间是哪个。 If self is the number, self.x raises an error. 如果self是数字,则self.x会引发错误。 (I'm maybe mistaking on this point : Is "other" always a number ?) (我可能会误解这一点:“其他”总是一个数字吗?)

So I found here : Python: multiplication override that I could do : 所以我在这里找到: Python:我可以做的乘法覆盖

__rmul__ = __mul__

but how can I do that in a class definition ? 但是我怎么能在课程定义中这样做呢?

Something like : 就像是 :

def __rmul__ = __mul__

self will never be the number in __mul__() because the object the method is attached to is not the number, it's the vector, and by definition it's the multiplicand. self永远不会是__mul__()的数字,因为方法所附加的对象不是数字,它是向量,根据定义它是被乘数。

other will be a number if your object is being multiplied by a number. 如果您的对象乘以数字,则other将是一个数字。 Or it could be something else, such as another vector, which you could test for and handle. 或者它可能是其他东西,例如另一个矢量,你可以测试和处理。

When your object is the multiplier, __rmul__() is called if the multiplicand doesn't know how to handle the operation. 当您的对象是乘数时,如果被乘数不知道如何处理该操作,则调用__rmul__()

To handle the case in which __mul__ and __rmul__ should be the same method, because the operation is commutative, you can just do the assignment in your class definition. 要处理__mul____rmul__应该是相同方法的情况,因为操作是可交换的,您可以在类定义中进行赋值。

class Vector(object):
    def __mul__(self, other):
        pass

    __rmul__ = __mul__

Simply list it as an attribute: 只需将其列为属性:

__rmul__ = __mul__

This is the same way you'd create an alias of a function in a module; 这与在模块中创建函数别名的方式相同; creating an alias of a method within a class body works the same. 在类体中创建方法的别名也是一样的。

The point is that in Python, you can tell objects how to multiply themselves by things. 关键是在Python中,您可以告诉对象如何通过事物来增加自己。 That means that 这意味着

a * b

could either mean "tell a to multiply itself by b " or "tell b to multiply itself by a ". 可能意味着“告诉a将自己乘以b ”或“告诉b将自己乘以a ”。 In code, that translates to 在代码中,转换为

a.__mul__(b)

or 要么

b.__rmul__(a)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM