日!我正在回答example in the docs并尝试创建类,其中__str__
替换为我的from decimal import *
class Zar(Decimal):
def __init__(self, z):
self.__z = Decimal(z)
def __str__(self):
return 'R{!r}'.format(self.__z)
def __repr__(self):
return 'R{!r}'.format(self.__z)
z1 = Zar(3.62)
z2 = Zar(4.12)
z = Zar(z1 + z2)
print('{:.3f}'.format(z))
print(z)
,如下所示:
R7.740
我期望输出像7.740
RDecimal('7.740000000000000213162820728')
,但它不起作用。
请 - 比如说 - 如何为标准类重新加载 str 方法?
做所有的+ - / * ...方法
现在我有输出:
public class PlayScreen implements Screen {
private TiledMap map;
private IsometricTiledMapRenderer isometricRenderer;
private OrthographicCamera camera;
public void createUI() {
// Load map from tiled .tmx file.
map = new TmxMapLoader().load("arena1/arena1.tmx");
// Setup isometric renderer and camera.
isometricRenderer = new IsometricTiledMapRenderer(map);
camera = new OrthographicCamera();
}
@Override
public void show() {
Gdx.gl.glClearColor(0, 0, 0, 1);
createUI();
}
@Override
public void render(float delta) {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
isometricRenderer.setView(camera);
isometricRenderer.render();
}
@Override
public void resize(int width, int height) {
camera.viewportWidth = width * 2;
camera.viewportHeight = height * 2;
camera.position.set(768, 0, 0);
camera.update();
}
@Override
public void pause() {}
@Override
public void resume() {}
@Override
public void hide() {}
@Override
public void dispose() {
map.dispose();
isometricRenderer.dispose();
}
}
答案 0 :(得分:1)
由于您选择的格式化字符串,而不是因为您使用的是RDecimal(...)
,因此您获得了R...
而不是Decimal.__str__
。
In [1]: import decimal
In [2]: a = decimal.Decimal(3.62)
In [4]: str(a)
Out[4]: '3.62000000000000010658141036401502788066864013671875'
In [5]: repr(a)
Out[5]: "Decimal('3.62000000000000010658141036401502788066864013671875')"
In [6]: 'R{!r}'.format(a)
Out[6]: "RDecimal('3.62000000000000010658141036401502788066864013671875')"
In [7]: 'R{}'.format(a)
Out[7]: 'R3.62000000000000010658141036401502788066864013671875'
因此,如果您只是将__str__
定义更改为return 'R{}'.format(self.__z)
,那么您应该没问题。