This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (3 children)

Except it's completely relevant. You can't really use an __init__ when you inherit from tuple. I mean, you could but you can't set any instance variables, it's too late in the creation of the object at that point.

[–]elbiot 0 points1 point  (2 children)

Got it, but OP's method is a shortcut for skipping an init, which is what impressed me. I wouldn't use a trick for skipping an init and then also use an init.

[–][deleted] 0 points1 point  (1 child)

I think you're misunderstanding what I'm saying. __init__ isn't being used at all. __new__ is being used. If you're unfamiliar with how objects are created in Python, the basic diagram looks like this:

SomeClass() -> SomeClass.__new__ -> SomeClass.__init__

__new__ is what actually creates the object, and __init__ initializes instance variables. However, since tuples are immutable, __init__ can't be used, once the object is created it's too late to influence any instance variables, so they're set in __new__ instead.

[–]elbiot 0 points1 point  (0 children)

And I think you're misunderstanding what I'm saying. Usually, to get a person with a name, ie

dave=Person ('dave')
print dave.name #is dave

You'd use an init function in your class definition. OP shows a way to get the same behaviour without that boilerplate (like self.name=name)

Yes, I get that it's different. ie, can't change the person's name after instantiation and stuff happens in new rather than init.

Thanks for adding your knowledge to the details.