我正在尝试在 Python 中实现一个非常基本的类 Java 维度类:
class Dimension(object):
def __init__(self, width, height):
self.__width = width
self.__height = height
@property
def width(self):
return self.__width
@property
def height(self):
return self.__height
d = Dimension(800, 400)
print d.width
print d.height
这很好用:d.width 返回一个 int=800,d.height 返回一个 int=400。
但是我该如何定义 d 应该返回一个 tuple=(800,400) 而不是
<__main__.Dimension object at 0xXXXXXXXX>
?
是否有类似于__repr__
的内置类函数?为了它?
如何定义自定义类的返回值?
还是我必须实现一种新类型?
谢谢
最佳答案
如果你想让你的类表现得像一个元组,继承自元组:
class Dimension(tuple):
然后覆盖__new__
方法来操作创建:
def __new__(cls, width, height):
tuple.__new__(cls, (width, height))
留给你:
class Dimension(tuple):
def __new__(cls, width, height):
return tuple.__new__(cls, (width, height)) # create tuple with 2 items
def __init__(self, *args):
self.width = args[0] # width is the first argument passed
self.height = args[1] # height is the next
>>> d = Dimension(800, 400)
>>> print(d)
(800, 400)
>>> print(d.width)
800
>>> print(d.height)
400
关于Python - 定义对象返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41700266/