【问题标题】:Write class such that calling instance returns all instance variables编写类,使得调用实例返回所有实例变量
【发布时间】:2021-05-08 10:56:36
【问题描述】:

我已经回答了我自己的问题 - 请参阅下面的答案
我正在写一堂课,我想要这种行为:

a = f(10,20)
some_funct(a.row) # some_function is given 10
some_funct(a.col) # some_function is given 20
some_funct(a)     # some_function is given a tuple of 10, 20  <-- THIS ONE :)

最后一个行为难倒我。我还没有看到任何涵盖这一点的例子。

到目前为止:

class f(object):
    """Simple 2d object"""
    row: int
    col: int

    def __init__(self, row, col):
        self.row = row
        self.col = col

显然我不想要另一种方法,例如 self.both = row, col。 我只想“调用”实例

我是新来的课程,所以欢迎任何改进。属性、setter、getter 等。

编辑 1: 将问题中的“print”替换为“some_function”,并修改标题

【问题讨论】:

    标签: python-3.x class return subclass subclassing


    【解决方案1】:
    class f(tuple):
        """Simple 2d object"""
        def __new__(cls, x, y):
            return tuple.__new__(f, (x, y))
    
        def __init__(self, x, y):
            self.col = x
            self.row = y
    
    foo = f(1,2)
    print(foo.col)
    >>>1
    print(foo.row)
    >>>2
    print(foo)
    >>>(1, 2)
    

    重要的是:
    如果你想让它表现得像一个元组,那么让它成为一个元组的子类。

    很多东西,但偶然发现了external site,它为我提供了有关要在此处搜索的关键字的线索。 SO问题是here,但我稍微修改了这个答案。
    我仍然有点困惑,因为另一个网站说在 init 中也使用 new 但没有给出明确的例子。

    【讨论】:

      【解决方案2】:

      从 python 3.7 开始引入dataclasses,他们的目标是创建主要包含数据的类。 Dataclasses 带有一些辅助函数,用于提取类属性字典/元组。例如

      from dataclasses import dataclass,asdict,astuple
      @dataclass
      class f:
       x: int
       y: int
      
      f_instance = f(10,20)
      asdict(f_instance) # --> {'x': 10, 'y': 20}
      astuple(f_instance) # -> (10,20)
      

      编辑我:另一种技术是使用namedtuple 例如:

      from collections import namedtuple
      f = namedtuple('p',['row','col'])
      a =f(10,20)
      a.row #-> 10
      a.col #-> 20
      

      【讨论】:

      • print(f_instance) 返回 main.f'>。我需要它返回 (10,20)
      • 如前所述,您需要使用 astuple 函数,即 astuple(f_instance),这将返回 (10,20)
      • 也许是一个替代问题。如果我分配 x = 1 我可以简单地 print(x) 并且它按照我在我的问题中想要的方式工作。 'x' 类是如何实现的,所以我可以在我的类中使用它来实现相同的功能。
      • 也许named tuple 应该工作? from collections import namedtuple f = namedtuple('p',['row','col']) a =f(10,20) a.row #--&gt; 10 a.col # --&gt; 20
      • 能否请您展示完整的书面课程
      【解决方案3】:

      这可能会有所帮助

      
      class f(object):
          """Simple 2d object"""
          row: int
          col: int
      
          def __init__(self, row, col):
              self.row = row
              self.col = col
      
          def some_funct(self):
              return (self.row, self.col)
      

      你可以访问喜欢

      a = f(10,20)
      a.some_funct() # (10, 20)
      # or
      row, col = a.some_funct()
      

      【讨论】:

      • 啊,是的,我目前正在使用 def some_funct 的这种方法解决方案,我发现它在我的代码中有些难看。也许是一个替代问题。如果我分配 x = 1 我可以简单地 print(x) 并且它按照我在我的问题中想要的方式工作。 'x' 类是如何实现的,所以我可以在我的类中使用它来实现相同的功能
      【解决方案4】:

      你可以这样做

      class f(object):
          """Simple 2d object"""
          row: int
          col: int
      
          def __init__(self, row, col):
              self.row = row
              self.col = col
      
          def __str__(self):
              return f"row = {row}, col = {col}"
      

      然后像这样打印

      a = f(10,20)
      
      print(a)     # row = 10, col = 20
      

      【讨论】:

      • 谢谢 Hillal,这不符合我的需要,但我的问题令人困惑。我已经修改了我的问题以消除令人困惑的打印调用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-21
      • 2022-12-22
      • 2013-12-05
      • 2019-02-01
      • 1970-01-01
      • 2012-05-20
      相关资源
      最近更新 更多