我可以为内置Python类型添加自定义方法/属性吗?

102 投票
9 回答
48829 浏览
提问于 2025-04-16 10:00

举个例子——假设我想在Python的字典类型中添加一个叫做helloWorld()的方法。我可以这样做吗?

JavaScript有一个原型对象,它可以这样工作。也许这不是个好设计,我应该去创建一个字典的子类,但那样的话只适用于那些子类,而我希望它能在所有未来的字典中都能使用。

在JavaScript中可以这样实现:

String.prototype.hello = function() {
    alert("Hello, " + this + "!");
}
"Jed".hello() //alerts "Hello, Jed!"

这里有一个有用的链接,里面有更多的例子—— http://www.javascriptkit.com/javatutors/proto3.shtml

9 个回答

9

注意: 这个问答被标记为重复,链接到 这个问题,但在我看来,它问的内容有所不同。我不能在那个地方回答,所以我在这里回答。


具体来说,我想从 str 这个类型继承,并添加一些自定义属性。现有的回答(尤其是那些说你不能的)并没有完全解决我的问题,但这个方法对我有效:

class TaggedString(str):
    """
    A ``str`` with a ``.tags`` set and ``.kwtags`` dict of tags.
    Usage example::
      ts = TaggedString("hello world!", "greeting", "cliche",
                        what_am_i="h4cker")
      (ts.upper(), ts.tags, ts.kwtags)
    """

    def __new__(cls, *args, **kwargs):
        return super().__new__(cls, args[0])

    def __init__(self, s, *tags, **kwtags):
        super().__init__()
        self.tags = set(tags)
        self.kwtags = kwtags

希望这能帮助到某个人!谢谢,
安德烈斯

10

我刚刚尝试了禁果!

这里是代码,非常简单!

from forbiddenfruit import curse


def list_size(self):
    return len(self)

def string_hello(self):
    print("Hello, {}".format(self))

if __name__ == "__main__":
    curse(list, "size", list_size)
    a = [1, 2, 3]
    print(a.size())
    curse(str, "hello", string_hello)
    "Jesse".hello()
104

你不能直接把方法加到原来的类型上。不过,你可以创建这个类型的子类,然后把它放到内置的全局命名空间里,这样就能实现大部分你想要的效果。可惜的是,用字面量语法创建的对象仍然会是原来的类型,不会拥有你新加的方法或属性。

下面是具体的例子

# 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 <module>
    print '0'.first_last()
AttributeError: 'str' object has no attribute 'first_last'
"""

撰写回答