I'm having trouble understanding scope of a variable in a subclass

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Thu Dec 28 00:02:29 EST 2006


On Thu, 28 Dec 2006 15:31:26 +1100, Pyenos wrote:

> Approach 1:
> 
> class Class1:
>         class Class2:
>                 def __init__(self):self.variable="variable"
> 
>                 class Class3:
>                         def method():print Class1().Class2().variable #problem

These are NESTED classes, not subclasses.

You say "#problem". What's the problem? What does it do that you don't
expect, or not do that you do expect? Does it crash your PC? Raise an
exception? Don't assume that we can guess what the problem is.

[snip multiple attempts]


 
> Is there a correct solution in the above? Or, what is the solution?

The solution to what problem? What are you trying to do? Why are you
nesting classes? Nesting classes isn't wrong, but it is quite advanced.
Let's do subclassing first.

class Parrot(object):
    """Parrot class."""
    plumage = "green"  # The default colour of parrots.
    def __repr__(self):
        return "A parrot with beautiful %s plumage." % self.plumage

class NorwegianBlue(Parrot):
    """Norwegian Blue class, subclass of Parrot."""
    plumage = "blue"


Now experiment with those two classes:

>>> p = Parrot()
>>> p
A parrot with beautiful green plumage.
>>> p.plumage = "red" # Change the instance.
>>> p
A parrot with beautiful red plumage.
>>> Parrot() # But the class stays the same.
A parrot with beautiful green plumage.
>>> q = NorwegianBlue()
>>> q
A parrot with beautiful blue plumage.
>>> q.plumage
'blue'
>>> super(NorwegianBlue, q).plumage
'green'


Does this help?


-- 
Steven D'Aprano 




More information about the Python-list mailing list