【问题标题】:How to mix normal and slice arguments in python如何在python中混合普通参数和切片参数
【发布时间】:2018-12-10 19:11:20
【问题描述】:

我有一个类,我想从一个数组中创建一个实例,外加一个切片。我希望语法使用例如使用的冒号语法。列表和 numpy 数组。以下示例是一个 MNWE(最小的非工作示例):

import numpy as np

class A():

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

    def __getitem__(self, index):
        return self.data.__getitem__(index)

    @classmethod
    def fromArray(cls, array, index):
        return cls(array.__getitem__(index))

x = np.empty((4, 2, 2)) 
a = A(x)
print(a[:, 0, 0]) 

# Create from array, using slices:
my_slices = (slice(0, -1, 1), slice(0, 1, None), slice(0, 1, None))
b = A.fromArray(x, my_slices)
print(b.data)

# Create from array, using slice colon syntax (fails):
c = A.fromArray(x, :, 0, 0)
print(c.data)

我希望结果是相同的,除了平面尺寸。

【问题讨论】:

  • MNWE 是什么意思?
  • @PeterWood “最小的非工作示例”?
  • @PeterWood 抱歉,已在文中更正。
  • Python 语言语法不能那样工作。不能在函数参数中使用切片语法。

标签: python slice numpy-ndarray


【解决方案1】:

我不知道您尝试做的是否可行。

创建一个工厂类怎么样?

class AFactory:
    def __init__(self, x):
        self.x = x

    def __getitem__(self, index):
        return A.fromArray(self.x, index)

c = AFactory(x)[:, 0, 0]
print(c.data)

或者如果您更喜欢在数组之前设置切片:

class AFactory:
    def __getitem__(cls, index):
        return lambda x: A.fromArray(x, index)

c = AFactory()[:, 0, 0](x)
print(c.data)

【讨论】:

    猜你喜欢
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    • 2011-10-03
    • 1970-01-01
    • 2016-05-12
    • 2023-03-28
    相关资源
    最近更新 更多