Reputation:
I want to give a class I made all of the methods that a string has (replace
, isupper
, etc.)
Below is some example code:
>>> class MyClass(str):
... def __init__(self, string):
... self.string = string
... def __str__(self):
... return self.string
...
>>> MyClass("aaa").replace("a", "$")
'$$$'
>>>
This works exactly as I want it to. However, I am a little confused on how I should inherit from str
. I can do as I did above, or:
class MyClass(__builtins__.str):
...
or even:
import types
class MyClass(types.__builtins__["str"]):
Summed up, my question is: what is the best way to inherit from str
(or any other built-in for that matter)? Did I give it or is there an even better way I'm not thinking of.
Thanks.
Upvotes: 0
Views: 98
Reputation: 280465
Never touch __builtins__
. It is an implementation detail. Quoting the docs for the confusingly similarly-named __builtin__
module:
CPython implementation detail: Most modules have the name
__builtins__
(note the 's') made available as part of their globals. The value of__builtins__
is normally either this module or the value of this modules’s dict attribute. Since this is an implementation detail, it may not be used by alternate implementations of Python.
Just inherit from str
. There's no reason not to; it's not faster or clearer or anything to use some other name for it.
Upvotes: 1
Reputation: 11070
class MyClass(str):
Is just fine. I do not think there is a problem with that. Why do you want to burden yourself by using builtin
and all...
Upvotes: 1