如何在 Python 中为字符串对象提供自定义方法?
How do I give a string object a custom method in Python?
类似于“.format”,我希望能够在字符串前自动添加时间前缀。我真的不知道该怎么做,但我认为它可能看起来像这样。
>>print("Function __init__ at CLASS myClass running...".log())
打印:
[myPrefix] Function init at CLASS myClass running...
我完全不知道我会怎么做。
遗憾的是,您甚至不能将属性猴子修补到内置类型上。这个:
def log(self):
print "logging "+self
str.log = log
str("hello")
print "hello".log()
给出:
Traceback (most recent call last):
Line 3, in <module>
str.log = log
TypeError: can't set attributes of built-in/extension type 'str'
最好的方法就是编写一个日志记录方法,如下所示:
def log(s):
print("my-prefix -- "+s)
log("hello")
这样做的好处是,如果在稍后阶段,您决定不打印您的日志记录语句,而是将它们通过管道传输到一个文件中,您只需要更改 log
函数,而不是许多你有打印语句的地方,例如:
def log(s):
with open("my_log.txt",w) as f:
data = f.write("the time - " + s)
log("hello")
现在,您所有的日志记录语句都转到文件中,而无需更改实际的日志记录调用。
类似于“.format”,我希望能够在字符串前自动添加时间前缀。我真的不知道该怎么做,但我认为它可能看起来像这样。
>>print("Function __init__ at CLASS myClass running...".log())
打印:
[myPrefix] Function init at CLASS myClass running...
我完全不知道我会怎么做。
遗憾的是,您甚至不能将属性猴子修补到内置类型上。这个:
def log(self):
print "logging "+self
str.log = log
str("hello")
print "hello".log()
给出:
Traceback (most recent call last):
Line 3, in <module>
str.log = log
TypeError: can't set attributes of built-in/extension type 'str'
最好的方法就是编写一个日志记录方法,如下所示:
def log(s):
print("my-prefix -- "+s)
log("hello")
这样做的好处是,如果在稍后阶段,您决定不打印您的日志记录语句,而是将它们通过管道传输到一个文件中,您只需要更改 log
函数,而不是许多你有打印语句的地方,例如:
def log(s):
with open("my_log.txt",w) as f:
data = f.write("the time - " + s)
log("hello")
现在,您所有的日志记录语句都转到文件中,而无需更改实际的日志记录调用。