Under normal circumstances, you can't add methods to an existing builtin object. Instead, the simple approach is to write a function that accepts the object you want to operate on:
def write(self):
print(self)
You can call an argument whatever you want, including self
. Now you can call it like this:
write('Hello World!')
If you were dealing with classes defined in Python rather than a builtin like str
, you could try monkey-patching your method right in:
class MyType:
def __init__(self, value):
self.value = value
To monkey-patch the class, so all instances see the method:
MyType.write = write
MyType('Hello World!').write()
To monkey-patch just a single instance:
instance = MyType('Hello World!')
instance.write = write.__get__(instance)
instance.write()
All that being said, the proper approach to modifying existing classes with new functionality is to subclass. You are free to extend str
with any functionality you see fit:
class MyType(str):
def write(self):
print(self)
The only thing that will differ from your example is that your class is not special and can no longer be initialized from a literal. In all other respects, it will behave like a string with a write
method:
s = MyType('Hello World!')
s.write()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…