900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > python自定义类的属性_我可以将自定义方法/属性添加到内置Python类型吗?

python自定义类的属性_我可以将自定义方法/属性添加到内置Python类型吗?

时间:2023-09-21 14:57:16

相关推荐

python自定义类的属性_我可以将自定义方法/属性添加到内置Python类型吗?

For example—say I want to add a helloWorld() method to Python's dict type. Can I do this?

JavaScript has a prototype object that behaves this way. Maybe it's bad design and I should subclass the dict object, but then it only works on the subclasses and I want it to work on any and all future dictionaries.

Here's how it would go down in JavaScript:

String.prototype.hello = function() {

alert("Hello, " + this + "!");

}

"Jed".hello() //alerts "Hello, Jed!"

解决方案

You can't directly add the method to the original type. However, you can subclass the type then substitute it in the built-in/global namespace, which achieves most of the effect desired. Unfortunately, objects created by literal syntax will continue to be of the vanilla type and won't have your new methods/attributes.

Here's what it looks like

# Built-in namespace

import __builtin__

# Extended subclass

class mystr(str):

def first_last(self):

if self:

return self[0] + self[-1]

else:

return ''

# Substitute the original str with the subclass on the built-in namespace

__builtin__.str = mystr

print str(1234).first_last()

print str(0).first_last()

print str('').first_last()

print '0'.first_last()

output = """

14

00

Traceback (most recent call last):

File "strp.py", line 16, in

print '0'.first_last()

AttributeError: 'str' object has no attribute 'first_last'

"""

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。