【问题标题】:How to a, b = myClass(a, b) in Python?如何在 Python 中实现 a, b = myClass(a, b)?
【发布时间】:2020-03-11 21:00:07
【问题描述】:

Python 会这样做:

t = (1, 2)
x, y = t
# x = 1
# y = 2

我怎样才能实现我的课程呢

class myClass():
    def __init__(self, a, b):
        self.a = a
        self.b = b

mc = myClass(1, 2)
x, y = mc
# x = 1
# y = 2

有没有我可以实现的神奇功能来实现这一点?

【问题讨论】:

  • tuple(1, 2) 不是有效的tuple 调用。
  • @user2357112 我修复了它,以及__init__ 方法

标签: python python-3.x iterable-unpacking magic-function


【解决方案1】:

你需要让你的班级iterable。通过向其添加__iter__ 方法来执行此操作。

class myClass():
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __iter__(self):
        return iter([self.a, self.b])

mc = myClass(1, 2)

x, y = mc

print(x, y)

输出:

1 2

【讨论】:

  • 我可以做到这一点的元范围怎么样? myClass_atrributename = myClass(a, b)。因此,如果您的类有一个名为“myClass_attributename”的属性来返回该值
  • 我不确定我是否理解
  • 我认为@entropyfeverone 可能试图引用getattr?喜欢getattr(myclass(a, b), 'myClass_attributename')
【解决方案2】:

如果您的班级没有做太多其他事情,您可能更喜欢使用named tuple

from collections import namedtuple

MyClass = namedtuple('MyClass', 'a b')
mc = MyClass(1, 2)
print(mc.a, mc.b)  # -> 1 2
x, y = mc
print(x, y)  # -> 1 2

顺便说一句,样式说明:类名应该是 UpperCamelCase。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    • 2021-11-28
    • 1970-01-01
    • 2014-03-29
    • 2019-12-28
    • 2021-10-06
    • 1970-01-01
    相关资源
    最近更新 更多