编写类以便调用实例返回所有实例变量

问题描述

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

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”,并修改标题

解决方法

你可以这样做

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
,

从 python 3.7 dataclasses 开始,它们的目标是创建主要包含数据的类。 Dataclasses 带有一些辅助函数,用于提取类属性 dict/tuples。例如

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
,

这可能有帮助


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

    def __init__(self,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()
,
class f(tuple):
    """Simple 2d object"""
    def __new__(cls,x,y):
        return tuple.__new__(f,(x,y))

    def __init__(self,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 但没有给出明确的例子。