Summary: please, let's not encourage this use of nested classes. > > Can someone provide a reason why you'd want to use nested classes? > > I've never felt this need myself. What are the motivations? > > For example, I find it natural to use a nested class to provide an > iterator object for a class that defines __iter__, in many cases. [Example deleted] Why do you find this natural? Perhaps because you've written a lot of Java? I find it "not natural" -- I have used this pattern (a helper class) many times but have never felt the urge to nest the helper inside the outer class (let alone inside a method of the outer class). > Of course, I could define that "class Inner" in any place at all, > but since it's only meant to be used in this one spot, why not > define it right here? I think it enhances legibility -- if I put it > elsewhere, the reader of the code seeing just the return statement > in the def __iter__ must go look elsewhere to see what I'm doing, > and/or if the reader sees class Inner on its own it may not be > equally obvious what it's meant to be used for, while with this > placement it IS abundantly obvious. It's already been pointed out that placing it inside the __iter__ method is a bad idea because of performance. I also think that it's better that the iterator class *is* accessible to the user -- that way you can do an isinstance() check for it, for example. The legibility argument is dubious: in a realistic example, the iterator class may easily be fairly big, and that makes it a disruptive detail for the reader of the Outer class. > There are other wrapping/adaptation examples that work similarly, > where I need a class just inside one particular method or function > because the only reason for that class's existence is to be suitably > instantiated to wrap another object and adapt it to some externally > imposed protocol. I like being able to nest such "local use only" > wrapper classes in the one and only place where they're needed: > by being right there they enhance readability as outlined in the > previous paragraph, in my opinion. It's still a bad idea. --Guido van Rossum (home page: http://www.python.org/~guido/)
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4