Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending builtin classes in python

How can I extend a builtin class in python? I would like to add a method to the str class.
I've done some searching but all I'm finding is older posts, I'm hoping someone knows of something newer.

like image 890
UnkwnTech Avatar asked Dec 09 '08 12:12

UnkwnTech


People also ask

How do you extend an existing class in Python?

Another way to extend (specifically meaning, add new methods, not change existing ones) classes, even built-in ones, is to use a preprocessor that adds the ability to extend out of/above the scope of Python itself, converting the extension to normal Python syntax before Python actually gets to see it.

What is super () __ Init__ in Python?

When you initialize a child class in Python, you can call the super(). __init__() method. This initializes the parent class object into the child class. In addition to this, you can add child-specific information to the child object as well.

How polymorphism is achieved in Python?

As is the case with other programming languages like as Java and C++, polymorphism is implemented in Python for a variety of purposes, most notably Duck Typing, Operator and Method overloading, and Method overriding. This polymorphism may be accomplished in two distinct ways: overloading and overriding.


2 Answers

Just subclass the type

>>> class X(str): ...     def my_method(self): ...         return int(self) ... >>> s = X("Hi Mom") >>> s.lower() 'hi mom' >>> s.my_method() Traceback (most recent call last):   File "<stdin>", line 1, in <module>   File "<stdin>", line 3, in my_method ValueError: invalid literal for int() with base 10: 'Hi Mom'  >>> z = X("271828") >>> z.lower() '271828' >>> z.my_method() 271828 
like image 89
S.Lott Avatar answered Sep 28 '22 03:09

S.Lott


One way could be to use the "class reopening" concept (natively existing in Ruby) that can be implemented in Python using a class decorator. An exemple is given in this page: http://www.ianbicking.org/blog/2007/08/opening-python-classes.html

I quote:

I think with class decorators you could do this:

@extend(SomeClassThatAlreadyExists) class SomeClassThatAlreadyExists:     def some_method(self, blahblahblah):         stuff 

Implemented like this:

def extend(class_to_extend):     def decorator(extending_class):         class_to_extend.__dict__.update(extending_class.__dict__)         return class_to_extend     return decorator 
like image 43
lll Avatar answered Sep 28 '22 04:09

lll