将一个自定义类的序列映射到另一个自定义类的Pythonic方法是什么?

时间:2015-09-30 13:42:11

标签: python type-conversion

(...或者,C#的Select(...)方法的Pythonic版本是什么?)

给定自定义类l的列表A,将l的每个元素映射到不同的自定义类B的(大多数?)Pythonic方法是什么?

例如,以下代码将执行此操作,但它是最恐怖的方式吗?注意,真实类型有很多属性。

l = [A('Greg', 33), A('John', 39)]

def map_to_type_b(the_list):
    new_list = []
    for item in the_list:
        new_list.append(B(item.name, item.age))

    return new_list

l2 = map_to_type_b(l)

我来自C#背景,我将使用LinQ selectSelect()扩展方法从源序列投射到类型B的新序列。< / p>

2 个答案:

答案 0 :(得分:1)

我会说B类的工作的一部分是确定如何将某个任意其他类的实例转换为B的实例,所以我会使用类方法备用构造方法,例如如下:

class A(object):

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return 'A({0.name!r}, {0.age!r})'.format(self)


class B(A):

    def __repr__(self):
        return 'B({0.name!r}, {0.age!r})'.format(self)

    @classmethod
    def from_A(cls, inst):
        return cls(inst.name, inst.age)

然后,您可以使用简单的列表推导甚至map将一个类的列表转换为另一个类,例如:

>>> l = [A('Greg', 33), A('John', 39)]
>>> l
[A('Greg', 33), A('John', 39)]

>>> map(B.from_A, l)  # will look different, but is more memory-efficient, in 3.x
[B('Greg', 33), B('John', 39)]

>>> [B.from_A(a) for a in l]  # works (nearly) identically in 2.x and 3.x
[B('Greg', 33), B('John', 39)]

答案 1 :(得分:1)

编写仅限数据的对象不仅在Python中,而且在大多数基于OO的语言中都不受欢迎。也许最恐怖的方式可能是传递平面数据,比如说,一个字典或一系列字母:

{'Greg': 33, 'John': 39}

[{'name': 'Greg', 'age': 33}, {'name': 'John', 'age': 39}]

那就是说,假设你有A类和B类,并且想要从现有的A实例中实例化新的B:

class A(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return '<{cls} name={s.name}, age={s.age}>'.format(
            cls=self.__class__.__name__,
            s=self
        )

class B(A):
    def __init__(self, name, age, born_as='male'):
        super(B, self).__init__(name, age)
        self.born_as = born_as

data = {'Greg': 33, 'John': 39}
list_of_a = [A(k, v) for k, v in data.items()]

你可以保持简单明了:

>>> list_of_a
[<A name=Greg, age=33>, <A name=John, age=39>]

>>> [B(a.name, a.age) for a in list_of_a]
[<B name=Greg, age=33>, <B name=John, age=39>]

如果涉及很多属性,这可能会有点冗长。让我们教B如何克隆A:

class B(A):
    def __init__(self, name, age, born_as='male'):
        super(B, self).__init__(name, age)
        self.born_as = born_as

    @classmethod
    def clone(cls, instance, *args, **kwargs):
        return cls(instance.name, instance.age, *args, **kwargs)

由于B现在知道如何克隆A:

>>> [B.clone(a) for a in list_of_a]
[<B name=Greg, age=33>, <B name=John, age=39>]        

为所有类似B的类编写克隆方法会很繁琐。内省是非常恐怖的,所以不要重复自己:

class CloneFromInstanceMixin(object):
    @classmethod
    def clone(cls, instance, **kwargs):
        constructor_args = inspect.getargspec(instance.__init__).args
        for attr_name in constructor_args:
            if attr_name in kwargs:
                continue # overrides instance attribute
            try:
                kwargs[attr_name] = getattr(instance, attr_name)
            except AttributeError:
                pass
        return cls(**kwargs)

class B(CloneFromInstanceMixin, A):
    def __init__(self, name, age, born_as='male'):
        super(B, self).__init__(name, age)
        self.born_as = born_as

>>> [B.clone(a) for a in list_of_a]
[<B name=Greg, age=33>, <B name=John, age=39>]   

我可能有太多的空闲时间。

相关问题