Classes in a class: how to access variables from one in another

Gary Herron gherron at islandtraining.com
Mon Oct 18 16:05:51 CEST 2010


  On 10/18/2010 06:45 AM, fab at slick.airforce-one.org wrote:
> Neil Cerutti<neilc at norwich.edu>  wrote:
>>> I have a class A that contains two classes B and C:
>>>
>>> class A:
>>>    class B:
>>>      self.x = 2
>>>
>>>    class C:
> I only wanted to show the structure of the code, not the actual
> instructions.
>
>> That's not valid Python code. Do you mean:
>>
>> Class A:
>>   Class B:
>>     x = 2
>> Class A:
>>   Class B:
>>     def __init__(self):
>>       self.x = 2
>>
> Any of these, aslong as I can access x  in C.
>
> By the way, is the first proposition (that is, x = 2, without the
> self.) valid? Is x a global variable then?
>
> Thanks.
>
Well, your code still doesn't make sense, but the generic answers are:

This defines a class variable:
class A:
   x=123
and access to the variable is
   A.x

This defines an instance variable:
class A:
   def __init__(self):
     self.x = 123
and once you have an object of class A,
   a = A()
access is
   a.x
from outside the class, and
   self.x
from inside the class.
(Those are really the same, the instance is named 'a' in one case and 
'self' in the other.)

If *any* object, class or instance of a class (or module or whatever) 
contains another, access is by chaining the dots.
   OuterOb.InnerOb.attribute


Hope that answers your question.

Gary Herron




More information about the Python-list mailing list