Can I add custom methods/attributes to built-in Python types?

Posted by sfjedi on Stack Overflow See other posts from Stack Overflow or by sfjedi
Published on 2011-01-15T07:27:10Z Indexed on 2011/01/15 7:53 UTC
Read the original article Hit count: 295

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!"

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

© Stack Overflow or respective owner

Related posts about python

Related posts about custom-attributes