首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为自定义类赋值

为自定义类赋值
EN

Stack Overflow用户
提问于 2019-06-08 15:19:28
回答 1查看 69关注 0票数 0

我想创建一个自定义数组对象。我想要实现的函数之一是可以添加两个不同长度的数组,或多或少如下所示

代码语言:javascript
运行
复制
[1, 2, 3] + [4, 5] = [5, 7, 3]

我的自定义类的定义如下

代码语言:javascript
运行
复制
class MyArray:

    def __init__(self, values):
        self.values = values

    def __len__(self):
        return len(self.values)

    def __getitem__(self, key):
        """Makes MyArray sliceable"""
        if isinstance(key, slice):
            return self.values[key.start:key.stop:key.step]
        else:
            return self.values[key]

    def __add__(self, other):
        """"Make addition of two MyArrays of different lengths possible."""
        if len(self) >= len(other):
            a = self
            b = other
        else:
            a = other
            b = self
        a[:len(b)] += b[:]
        return MyArray(a)

然而,有些东西是缺失的。我猜这里有一些关于切片实现的东西。

代码语言:javascript
运行
复制
import numpy as np

a = MyArray(np.array([1,2,3]))
b = MyArray(np.array([4,5]))

直接赋值失败

代码语言:javascript
运行
复制
a[2] = 3
Traceback (most recent call last):

  File "<ipython-input-8-17351fe6de12>", line 1, in <module>
    a[2] = 3

TypeError: 'MyArray' object does not support item assignment

显然,由于直接赋值失败,我的__add__方法也失败了。

代码语言:javascript
运行
复制
c = a + b

File "<ipython-input-1-2ce5425b4430>", line 28, in __add__
  a[:len(b)] += b[:]

TypeError: 'MyArray' object does not support item assignment
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-08 15:35:19

除了my comment之外,我还修复了__getitem____add__函数中的一些问题(在代码中添加了注释),所以我将作为答案发布:

代码语言:javascript
运行
复制
class MyArray:
    def __init__(self, values):
        self.values = values

    def __len__(self):
        return len(self.values)

    def __getitem__(self, key):
        """Makes MyArray sliceable"""
        return self.values[key]  # you don't need to check for slice, it is supported by default

    def __add__(self, other):
        """"Make addition of two MyArrays of different lengths possible."""
        if len(self) >= len(other):
            a = self
            b = other
        else:
            a = other
            b = self
        a = MyArray(a.values)  # you need to make a copy before addition
        a[:len(b)] += b[:]
        return a

    def __setitem__(self, key, value):
        self.values[key] = value

import numpy as np

a = MyArray(np.array([1,2,3]))
b = MyArray(np.array([4,5]))

a[2] = 4
c = a + b
print(c.values)  # [5 7 4]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56504344

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档