简体   繁体   English

创建用Python打印整数的装饰器

[英]Create a Decorator Printing An Integer in Python

I'd like to create a decorator that prints units on a number. 我想创建一个在数字上打印单位的装饰器。

money = 10
print(money)

results in '10 dollars' 结果为“ 10美元”

money = 1
print(money)

results in '1 dollar' 结果为“ 1美元”

I get that I need to wrap money.__str__() , but I'm not sure how to do that generically with a decorator. 我知道我需要把money.__str__() ,但是我不确定如何用装饰器来做。

Am I on the right track here? 我在正确的轨道上吗? Can the following somehow become a decorator? 以下内容能以某种方式成为装饰者吗?

def str_cur(money):
    if money == 1 or money == -1:
       return f"{money} dollar"
    else
       return f"{money} dollars"

Decorators in Python apply to functions (and more rarely, classes), not to variables. Python中的装饰器适用于函数(很少是类),而不适用于变量。 So I think investigating their syntax is not going to help you. 因此,我认为研究它们的语法不会对您有帮助。

It sounds like you might be able to do what you want by creating a class for your money that wraps up the integer. 听起来您可以通过创建一个包装整数的货币类来完成您想做的事情。 Your class can have a __str__ method that includes the currency name along with the number: 您的课程可以使用__str__方法,该方法包含货币名称和数字:

class Dollars(int):
    def __str__(self):
        if abs(self) == 1:
            return f"{self} dollar"
        else
            return f"{self} dollars"

Now you could do: 现在您可以执行以下操作:

money = Dollars(10)
print(money) # prints "10 dollars"

The Dollar class I wrote above inherits from int , so you can do all the normal numerical operations on it, but you will often get a normal int object back instead of another Dollar instance. 我在上面编写的Dollar类继承自int ,因此您可以对它进行所有常规的数值运算,但是您通常会得到一个普通的int对象,而不是另一个Dollar实例。 If you want to only get dollars back, you'd need to write your own versions of the numeric methods, which alas is rather tedious (you'd probably want to stop inheriting from int and just have an integer attribute). 如果您只想取回美元,则需要编写自己的数字方法版本,可惜这很繁琐(您可能希望停止从int继承,而只具有integer属性)。 If you only need to support a limited number of numeric options (like adding and subtracting dollar amounts from each other and multiplying and dividing by integers) it might not be too bad. 如果您只需要支持有限数量的数字选项(例如彼此相加和相减美元金额以及乘以除以整数),那可能还不错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM