编写类,以便调用实例返回所有实例变量 [英] Write class such that calling instance returns all instance variables
问题描述
我已经回答了我自己的问题-参见下面的答案
我正在写一个类,并且我想要这种行为:
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
我是班上的新手,所以我们欢迎您进行任何改进.属性,设置器,获取器等.
I'm new to classes, so any improvements are welcome. Properties, setters, getters etc.
替换为打印"带有"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问题是此处,但我对此答案做了一些修改.
我仍然有些困惑,因为另一个站点表示也要在初始化中使用 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屋!