Calling a variable inside a function of another class

Yigit Turgut y.turgut at gmail.com
Sat Jan 7 11:18:10 EST 2012


On Jan 7, 6:01 pm, Steven D'Aprano <steve
+comp.lang.pyt... at pearwood.info> wrote:
> On Sat, 07 Jan 2012 07:00:57 -0800, Yigit Turgut wrote:
> > I am trying to call a variable located in a function of a class from
> > main but couldn't succeed.Any ideas?
>
> You cannot access local variables from outside their function. That's why
> they are called *local* variables.
>
> You probably want to access *attributes* of the class or the instance.
> You have to define them first -- you can't access something that doesn't
> exist.
>
> class Test:
>     shared = 42  # Shared, class attribute
>     def __init__(self):
>         self.dt = 23  # Instance attribute, not shared.
>
> print(Test.shared)  # prints 42
>
> However, print(Test.dt) fails because no instance has been created yet,
> and so there is no dt attribute. You have to create an instance first,
> then __init__ will run and create the attribute:
>
> instance = Test()
> print(instance.dt)  # prints 23
>
> --
> Steven

How about assigning the variable as global, wouldn't it be more
effective?



More information about the Python-list mailing list