Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
Can 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!
Chris FreemanTreehouse Moderator 68,166 Points
Good 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 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.
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
# 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!