Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialZoe Wong
4,028 PointsCan I use the same name for the subclass as the parent class? What will happen if I do?
I'd like to add a method to a built-in class, but if I try to use setattr I get "TypeError: can't set attributes of built-in/extension type 'str'" (or whatever built-in I'm trying to add the method to).
Would it be possible to accomplish this by creating a subclass and naming it after the parent class?
For instance, using Kenneth's example of a reversed string method:
class str(str):
def reverse_string(*args, **kwargs):
self = str.__new__(*args, **kwargs)
self = self[::-1]
return self
How would I be able to access that reverse_string method? Could I call it like I'd call a built-in method like .upper()? Is it a bad idea to do this?
I'm pretty confused about the exact rules of subclassing and am not sure if this will break things. Any explanations would be much appreciated!
1 Answer
Chris Freeman
Treehouse Moderator 68,441 PointsGood question! When you create an object, it will override all other use of its name in the local namespace or context
>>> class str(str):
... def reverse_string(self):
... print("1:", id(self))
... self = self[::-1]
... print("2:", id(self))
... return self
...
>>> s0 = str("myself")
>>> id(s0)
140367721514704
>>> r0 = s0.reverse_string()
1: 140367721514704
2: 140367721544944
>>> id(r0)
140367721544944
>>> id(s0)
140367721514704
>>> s0
'myself'
Since strings are immutable, you cannot modify them. Assigning self[::-1]
to self
creates a new instance and does not override the old definition. You can see that the instances change by examining the id()
of each object.
While str
will take on the new definition, note the error raise when defining a string using simple quotes. The issue here is the syntax of bare quotes causes a call to __builtins__.str
to create the new string. This bypasses the locally defined str
.
# also...
>>> other = "1 2 3 4"
>>> other.reverse_string()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'reverse_string'
Post back if you have more questions. Good luck!