用户定义类型的输出格式 [英] output formatting for user-defined types

查看:63
本文介绍了用户定义类型的输出格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得模仿

内置输出格式的我自己的类的输出格式。例如,

I''d like to get output formatting for my own classes that mimics the
built-in output formatting. For example,

x = 4.54
print"%4.2f" %x
x = 4.54
print "%4.2f" % x




4.54


换句话说,如果我用一个类实例替换英寸×"我将

想要将格式字符串应用于

实例的一个或多个元素。那可能吗?如果是这样,怎么样?谢谢。



4.54

In other words, if I substitute a class instance for "x" above, I''d
like to make the format string apply to an element or elements of the
instance. Is that possible? If so, how? Thanks.

推荐答案

Russ写道:
我想得到我自己的输出格式模仿
内置输出格式的类。例如,

I''d like to get output formatting for my own classes that mimics the
built-in output formatting. For example,

x = 4.54
print"%4.2f" %x

4.54

换句话说,如果我用一个类实例替换x我将
想要将格式字符串应用于
实例的一个或多个元素。那可能吗?如果是这样,怎么样?谢谢。
x = 4.54
print "%4.2f" % x

4.54

In other words, if I substitute a class instance for "x" above, I''d
like to make the format string apply to an element or elements of the
instance. Is that possible? If so, how? Thanks.




我相信在你班上实施特殊方法__float__

就足够了。


class X:

def __float __(self):

返回3.14



I believe implementing the special method __float__ on your class
should be sufficient.

class X:
def __float__(self):
return 3.14

print''%f''%X ()
print ''%f'' % X()



3.140000


-Peter


3.140000

-Peter


谢谢,但这对我的应用程序来说是不可接受的。还有其他什么想法吗?


我以为我可以重载__rmod__,但显然python

在@_rmod__之前应用%运算符如果左边 - 手

参数是一个字符串。

Thanks, but that is not acceptable for my application. Any other ideas?

I thought I might be able to overload __rmod__, but apparently python
applies the % operator before __rmod__ is even invoked if the left-hand
argument is a string.


Russ写道:
谢谢,但那不是我的申请可以接受。还有其他什么想法吗?
Thanks, but that is not acceptable for my application. Any other ideas?




是的,我们如何阅读你的想法或猜测为什么它不能接受,并且b $ b不可接受,以及关于你的要求到底是什么。


真的,你的回答对我来说有点奇怪,因为__float__

是float()的定义方式从实例中获取值,并且
float()是%运算符在

格式字符串中遇到''%f'时调用的内容。 />

-Peter



Yeah, how about we read your mind or make wild guesses about why it''s
not acceptable, and about what your requirements really are.

Really, your response seems a little bizarre to me, given that __float__
is the defined way in which float() gets a value from an instance, and
float() is what the % operator calls when it encounters a ''%f'' in the
format string.

-Peter


这篇关于用户定义类型的输出格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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