MFB
MFB

Reputation: 19797

What is the best way to overwrite a Python Class __str__ method?

In my app, I want all my datetime.__str__() to return differently to the default. Is it ok to simply inherit and overwrite the method?

class datetime(datetime):
    def __str__(self):
        return self.strftime('%d-%m-%y %H:%M:%S')

Any advice would be great.

Upvotes: 3

Views: 1266

Answers (2)

jasisz
jasisz

Reputation: 1298

It's quite a philosophical question :) Generally in Python we don't like such things. You now must use your own class and always remember to use it instead of default datetime (which is hard to maintain if they have the same name). Ruby guys would just monekypatch datetime, which I consider even worse.

I would personally not even inherit it with different name (it would be confusing me also), but make some shortcut function outside any class and use it directly.

Upvotes: 0

AI Generated Response
AI Generated Response

Reputation: 8835

Generally, you will want to name your new class something other than one defined in the builtin modules, but yes, that is how you do it. Please for the sake of your sanity do not create a class definition using the same name as a predefined class.

I just tried to do the class datetime(datetime) bit, and it does work, at least in the interpreter, but any python expert will probably laugh or shudder.

Upvotes: 3

Related Questions