[Tutor] How can I access a variable outside a class definition?

Kirby Urner urnerk at qwest.net
Sat Sep 29 23:51:07 CEST 2001


>
>Is it possible to access,in the Outside class, a value of
>the ImSum
>that was return by
>Add function in that Complex class?

Classes have access to variables defined outside of them, e.g.

  >>> c = 10  # defined outside (e.g. returned by yr Complex.Add())

  >>> class C:
          def func(a,b):
             return a+b+c
          func =staticmethod(func)


  >>> C.func(1,2)
  13


is legal in 2.2 (the staticmethod syntax allows C to not
have a self -- a new breed of soulless classes is afoot).

If you're seriously wanting to do stuff with complex numbers,
please realize that they're already built in:

   >>> z1 = complex(1,2)
   >>> z2 = complex(3,4)
   >>> z3 = z1 + z2
   >>> z3
   (4+6j)
   >>> z3.real
   4.0
   >>> z3.imag
   6.0

-- all without even importing the cmath module.

Kirby







More information about the Python-list mailing list