编写类,使得调用实例返回所有实例变量 [英] Write class such that calling instance returns all instance variables

查看:21
本文介绍了编写类,使得调用实例返回所有实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have answered my own question - see answer below
I'm writing a class, and I want this behavior:

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 :)

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

The last behavior is stumping me. I have not seen any examples that cover this.

到目前为止:

Thus far:

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.我只想调用"实例

Explictly I do not want another method, say, self.both = row, col. I just want to 'call' the instance

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

I'm new to classes, so any improvements are welcome. Properties, setters, getters etc.

编辑 1:替换了打印"带有some_function"在问题中,并修改标题

EDIT 1: Replaced "print" with "some_function" in the question, and modified title

推荐答案

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)

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

Importantly:
If you want it to behave like a tuple then make it a subclass of tuple.

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

Much stuffing around but stumbled upon an external site which gave me clues about the keywords to search on here. The SO question is here but I have modified that answer slightly.
I'm still a little confused because the other site says to use new in the init as well but does not give a clear example.

这篇关于编写类,使得调用实例返回所有实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆