简体   繁体   中英

python adding new methods to built-in types

How would I go about writing python functions that can be append to strings (or other object)?

for example:

"FOO".lower()

How do they receive input? Are they generators?

I will happily read up on it, but I don't really know what I am looking for.

Strings are objects and thus have methods. lower() is one of them.

You cannot add a custom method to str , unicode or any other builtin (written in C) classes - see Implementing a custom string method and Extending builtin classes in python

They are not generators. They are simply methods defined on the string class.

You could create your own like this:

>>> class MyString(str):
...   def reversed(self):
...     return self[::-1]
... 
>>> x = MyString('spam and eggs')
>>> x.reversed()
'sgge dna maps'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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