Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 509
jedmao Avatar asked Jan 15 '11 07:01

jedmao


People also ask

Can methods have attributes in Python?

Everything in Python is an object, and almost everything has attributes and methods.

What are built-in attributes methods in Python?

They are used to implement access controls of the classes. Attributes of a class can also be accessed using the following built-in methods and functions : getattr() – This function is used to access the attribute of object. hasattr() – This function is used to check if an attribute exist or not.

Can methods have attributes?

A method could also utilize the attributes that you defined within the object itself. Another key difference between a method and attribute is how you call it. For example, let's say we create an instance using the above class we defined.


1 Answers

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' """ 
like image 65
TryPyPy Avatar answered Oct 07 '22 04:10

TryPyPy