我可以将自定义的方法/属性添加到内置的Pythontypes吗?

例如,比方说,我想为Python的字典types添加一个helloWorld()方法。 我可以这样做吗?

JavaScript有一个这样的原型对象。 也许这是不好的devise,我应该子类的字典对象,但它只能在子类上工作,我希望它在任何和所有未来的字典工作。

下面是在JavaScript中下载的方式:

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

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

您不能直接将该方法添加到原始types。 但是,您可以对该types进行子类化,然后将其replace为内置/全局命名空间,从而实现所需的大部分效果。 不幸的是,由字面语法创build的对象将继续是香草types,并不会有你的新方法/属性。

这是它的样子

 # 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' """ 

是的,通过inheritance这些types。 请参阅统一Python中的types和类 。

不,这并不意味着实际的词典将会有这种types,因为这会令人困惑。 子类化内buildtypes是添加function的首选方法。

子类化是Python中的一种方式。 多语言程序员学会在合理的情况下使用正确的工具。 Rails(一个使用Ruby的DSL)巧妙地构造的东西很难用像Python这样的更僵化的语言来实现。 人们经常比较两个说他们有多相似。 比较有些不公平。 Python以自​​己的方式闪耀。 totochto。