我正在学习Python中的绳索.当我尝试Foobar使用该print()函数打印类的对象时,我得到如下输出:
<__main__.Foobar instance at 0x7ff2a18c>
Run Code Online (Sandbox Code Playgroud)
有没有办法可以设置类及其对象的打印行为(或字符串表示)?例如,当我调用类对象时,我想以某种格式打印其数据成员.如何在Python中实现这一点?print()
如果您熟悉C++类,则可以通过为类ostream添加friend ostream& operator << (ostream&, const Foobar&)方法来实现上述标准.
我有一个矢量类,我定义了__mul__将矢量乘以数字的方法.
这是__mul__方法:
def __mul__(self, other):
x = self.x * other
y = self.y * other
new = Vector()
new.set_pos((x, y))
return new
Run Code Online (Sandbox Code Playgroud)
我的问题是我不知道数字和矢量之间是哪个.如果self是数字,则self.x会引发错误.(我可能会误解这一点:"其他"总是一个数字吗?)
__rmul__ = __mul__
Run Code Online (Sandbox Code Playgroud)
但是我怎么能在课程定义中这样做呢?
就像是 :
def __rmul__ = __mul__
Run Code Online (Sandbox Code Playgroud) python overriding class operator-overloading operator-keyword
在熟悉 时numpy,我注意到numpy数组中有一个有趣的行为:
import numpy as np
arr = np.array([1, 2, 3])
scale = lambda x: x * 3
scale(arr) # Gives array([3, 6, 9])
Run Code Online (Sandbox Code Playgroud)
将此与普通 Python 列表进行对比:
arr = [1, 2, 3]
scale = lambda x: x * 3
scale(arr) # Gives [1, 2, 3, 1, 2, 3, 1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
我很好奇这怎么可能。numpy数组是否覆盖乘法运算符或其他什么?
好的,所以我正在创建一个Vector类(数学向量,如[1,3]),我想将一个Vector实例与一个int相乘.首先,我实现了该__mul__方法,它工作正常.但是,这并不能解决问题.
a = Vector(4,3) # Creates a vector, [4,3]
a*4 # This works fine, and prints [16,12]
4*a # This, however, creates a TypeError (Unsupported operans type(s)).
Run Code Online (Sandbox Code Playgroud)
现在,这是可用的,但它可以更容易两种方式工作.有没有办法在Vector类中执行此操作?
我用 python 写了一个这样的类
class Vector(object):
def __init__(self, coordinates):
try:
if not coordinates:
raise ValueError
self.coordinates = tuple(coordinates)
self.dimension = len(coordinates)
except ValueError:
raise ValueError('The coordinates must be nonempty')
except TypeError:
raise TypeError('The coordinates must be an iterable')
def __add__(self,v):
v1 = np.array(self.coordinates)
v2 = np.array(v.coordinates)
result = v1 + v2
return result.tolist()
def __sub__(self, other):
v1 = np.array(self.coordinates)
v2 = np.array(other.coordinates)
result = v1 - v2
return result.tolist()
def __mul__(self, other):
return other * np.array(self.coordinates)
def multiply(self,other):
v = Decimal(str(other)) …Run Code Online (Sandbox Code Playgroud)