in the tree scopes in methods and classes when working out the meaning of names in class-based codeit helps to remember that classes introduce local scopesjust as functions doand methods are simply further nested functions in the following examplethe generate function returns an instance of the nested spam class within its codethe class name spam is assigned in the gener ate function' local scopeand hence is visible to any further nested functionsincluding code inside methodit' the in the "legbscope lookup ruledef generate()class spamcount def method(self)print(spam countreturn spam(spam is name in generate' local scope visible in generate' scopeper legb rule (egenerate(method(this example works in python since version because the local scopes of all enclosing function defs are automatically visible to nested defs (including nested method defsas in this exampleeven sokeep in mind that method defs cannot see the local scope of the enclosing classthey can see only the local scopes of enclosing defs that' why methods must go through the self instance or the class name to reference methods and other attributes defined in the enclosing class statement for examplecode in the method must use self count or spam countnot just count to avoid nestingwe could restructure this code such that the class spam is defined at the top level of the modulethe nested method function and the top-level generate will then both find spam in their global scopesit' not localized to function' scopebut is still local to single moduledef generate()return spam(class spamcount def method(self)print(spam countdefine at top level of module worksin global (enclosing modulegenerate(method(in factthis approach is recommended for all python releases--code tends to be simpler in general if you avoid nesting classes and functions on the other handclass nesting is useful in closure contextswhere the enclosing function' scope retains state used by the class or its methods in the followingthe nested method has access to its own scope advanced class topics