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

时间:2023-01-15 18:51:26

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

例如,假设我想为Python的dict类型添加一个helloWorld()方法。我可以这样做吗?

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.

JavaScript有一个以这种方式运行的原型对象。也许这是一个糟糕的设计,我应该对dict类型对象进行子类化,但是它只对子类起作用,我希望它可以对任何将来的字典起作用。

Here's how it would go down in JavaScript:

下面是JavaScript的情况:

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

Here's a useful link with more examples— http://www.javascriptkit.com/javatutors/proto3.shtml

下面是一个有更多示例的有用链接——http://www.javascriptkit.com/javatutors/proto3.shtml

3 个解决方案

#1


54  

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

#2


1  

Yes, by subclassing those types. See unifying types and classes in Python.

是的,通过子类化这些类型。请参阅在Python中统一类型和类。

No, this doesn't mean that actual dicts will have this type, because that would be confusing. Subclassing a builtin type is the preferred way to add functionality.

不,这并不意味着真正的裁判官会有这种类型,因为那样会让人困惑。对内置类型进行子类化是添加功能的首选方式。

#3


-1  

Subclassing is the way to go in Python. Polyglot programmers learn to use the right tool for the right situation - within reason. Something as artfully constructed as Rails (a DSL using Ruby) is painfully difficult to implement in a language with more rigid syntax like Python. People often compare the two saying how similar they are. The comparison is somewhat unfair. Python shines in its own ways. totochto.

子类化是Python中的一种方式。多门语言的程序员在合理的情况下学习使用正确的工具。像Rails这样巧妙构造的东西(使用Ruby的DSL)在一种语法更严格的语言(如Python)中很难实现。人们经常比较这两者有多相似。这种比较有点不公平。Python以自己的方式发光。totochto。

#1


54  

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

#2


1  

Yes, by subclassing those types. See unifying types and classes in Python.

是的,通过子类化这些类型。请参阅在Python中统一类型和类。

No, this doesn't mean that actual dicts will have this type, because that would be confusing. Subclassing a builtin type is the preferred way to add functionality.

不,这并不意味着真正的裁判官会有这种类型,因为那样会让人困惑。对内置类型进行子类化是添加功能的首选方式。

#3


-1  

Subclassing is the way to go in Python. Polyglot programmers learn to use the right tool for the right situation - within reason. Something as artfully constructed as Rails (a DSL using Ruby) is painfully difficult to implement in a language with more rigid syntax like Python. People often compare the two saying how similar they are. The comparison is somewhat unfair. Python shines in its own ways. totochto.

子类化是Python中的一种方式。多门语言的程序员在合理的情况下学习使用正确的工具。像Rails这样巧妙构造的东西(使用Ruby的DSL)在一种语法更严格的语言(如Python)中很难实现。人们经常比较这两者有多相似。这种比较有点不公平。Python以自己的方式发光。totochto。