Python类返回值 [英] Python class returning value
问题描述
我正在尝试创建一个返回值而不是自身的类。
I'm trying to create a class that returns a value, not self.
我将向您展示一个与列表进行比较的示例:
I will show you an example comparing with a list:
>>> l = list()
>>> print(l)
[]
>>> class MyClass:
>>> pass
>>> mc = MyClass()
>>> print mc
<__main__.MyClass instance at 0x02892508>
我需要MyClass返回一个列表,例如 list()
,而不是实例信息。我知道我可以做list的子类。但是有没有一种方法可以不用子类化呢?
I need that MyClass returns a list, like list()
does, not the instance info. I know that I can make a subclass of list. But is there a way to do it without subclassing?
我想模仿一个列表(或其他对象):
I want to imitate a list (or other objects):
>>> l1 = list()
>>> l2 = list()
>>> l1
[]
>>> l2
[]
>>> l1 == l2
True
>>> class MyClass():
def __repr__(self):
return '[]'
>>> m1 = MyClass()
>>> m2 = MyClass()
>>> m1
[]
>>> m2
[]
>>> m1 == m2
False
为什么 m1 == m2
错误吗?这就是问题。
Why is m1 == m2
False? This is the question.
很抱歉,如果我不回复大家。我正在尝试您提供给我的所有解决方案。我不能使用 def
,因为我需要使用setitem,getitem等函数。
I'm sorry if I don't respond to all of you. I'm trying all the solutions you give me. I cant use def
, because I need to use functions like setitem, getitem, etc.
推荐答案
如果您想要的是一种无需将 list
子类化就可以将类转换为列表的方法,则只需创建一个返回列表的方法即可: / p>
If what you want is a way to turn your class into kind of a list without subclassing list
, then just make a method that returns a list:
def MyClass():
def __init__(self):
self.value1 = 1
self.value2 = 2
def get_list(self):
return [self.value1, self.value2...]
>>>print MyClass().get_list()
[1, 2...]
如果您的意思是 print MyClass()
将打印一个列表,只需覆盖 __ repr __
:
If you meant that print MyClass()
will print a list, just override __repr__
:
class MyClass():
def __init__(self):
self.value1 = 1
self.value2 = 2
def __repr__(self):
return repr([self.value1, self.value2])
编辑:
我看到你的意思是如何使对象比较。为此,您可以覆盖 __ cmp __
方法。
I see you meant how to make objects compare. For that, you override the __cmp__
method.
class MyClass():
def __cmp__(self, other):
return cmp(self.get_list(), other.get_list())
这篇关于Python类返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!