Accessing a class's variable in Python

class Example(object): def the_example(self): itsProblem = "problem" theExample = Example() print(theExample.itsProblem)

How do I access a class's variable? I've tried adding this definition:

def return_itsProblem(self): return itsProblem

Yet, that fails also.

-------------Problems Reply------------

The anwser, in few words

In your example, itsProblem is a local variable.

Your must use self to set and get instance variables. You can set it in the __init__ method. Then your code would be:

class Example(object):
def __init__(self):
self.itsProblem = "problem"

theExample = Example()

But if you want a true class variable, then, use the class name directly:

class Example(object):
itsProblem = "problem"

theExample = Example()
print (Example.itsProblem)

But be careful with this one, as theExample.itsProblem is automatically set to be equal to Example.itsProblem, but is not the same variable at all and can be changed independently.

Some explanations

In Python, variables car be created dynamically. Therefor, you can do that:

class Example(object):

Example.itsProblem = "problem"

e = Example()
e.itsSecondProblem = "problem"

print Example.itsProblem == e.itsSecondProblem

Therefor, that's exactly what you do with the previous examples.

Indeed, in Python we use self as this, but it's a bit more than that. Self is the the first argument to any object method because the first argument is always the object reference. This is automatic, wherever you call it self or not.

Which means you can do:

class Example(object):
def __init__(self):
self.itsProblem = "problem"

theExample = Example()


class Example(object):
def __init__(my_super_self):
my_super_self.itsProblem = "problem"

theExample = Example()

It's exactly the same. The first argument of ANY object method is the current object, we only call it self as a convention. And you add just a variable to this object, the same way you would do it from outside.

Now, about the class variables. When you do:

class Example(object):
itsProblem = "problem"

theExample = Example()

You'll notice we first set a class variable, then we access an object variable. We never set this object variable but it works, how is that possible?

Well, Python tries to get first the object variable, but if he can't find it, will give you the class variable. Warning: the class variable is shared among instances, and the object variable is not.

As a conclusion, never use class variable to set default value to object variables. Use __init__ for that.

Eventually, you will learn that Python classes are instances and therefor object them-self, which give new lights to understand the above. Come back reading it again later, once you realize that.

You are declaring a local variable, not a class variable. To set an instance variable (attribute), use

class Example(object):
def the_example(self):
self.itsProblem = "problem" # <-- remember the 'self.'

theExample = Example()

To set a class variable (a.k.a. static member), use

class Example(object):
def the_example(self):
Example.itsProblem = "problem"
# or, type(self).itsProblem = "problem"
# depending what you want to do when the class is derived.

Category:python Views:0 Time:2010-08-08

Related post

  • how to access javascript variables in python 2012-03-31

    I am creating a facebook app and it uses Javascript API to store username and other details in js variables. And this app is created under Python(using Google App Engine). I want to access the js variables in Python and store the values in Db. How to

  • Simulating a 'local static' variable in python 2009-01-20

    Consider the following code: def CalcSomething(a): if CalcSomething._cache.has_key(a): return CalcSomething._cache[a] CalcSomething._cache[a] = ReallyCalc(a) return CalcSomething._cache[a] CalcSomething._cache = { } This is the easiest way I can thin

  • How do I do variable variables in Python? 2009-09-03

    How do I accomplish variable variables in Python? Here is an elaborative manual entry, for instance: Variable variables I hear this is a bad idea in general though, and it is a security hole in PHP. Is that true? --------------Solutions-------------

  • Differences between static and instance variables in python. Do they even exist? 2009-11-08

    A random class definition: class ABC: x = 6 Setting some values, first for the abc instance, later for the static variable: abc = ABC() abc.x = 2 ABC.x = 5 and then print the results: print abc.x print ABC.x which prints 2 5 Now, I don't really get w

  • declaring a global dynamic variable in python 2010-11-25

    I'm a python/programming newbie and maybe my question has no sense at all. My problem is that I can't get a variable to be global if it is dynamic, I mean I can do this: def creatingShotInstance(): import movieClass BrokenCristals = movieClass.shot()

  • calling class/static method from class variable in python 2011-02-15

    I'm trying to make a ImageLoader class handle the loading and processing of image resources like this: class ImageLoader: TileTable = __loadTileTable('image path', some other variable) @staticmethod def _loadTileTable(arg1, arg2): blah blah however,

  • How to set environment variables in Python 2011-05-11

    I am new to python. I have some scripts I inherited. I need to set some environment variables in the python script and I want all the other scripts that are called from python (shell scripts) which will be child process to see the environment variabl

  • passing bash variables to python script 2011-07-16

    What's the best way to pass bash variables to a python script. I'd like to do something like the following: $cat #!/bin/bash foo="hi" python -c 'import test; test.printfoo($foo)' $cat #!/bin/python def printfoo(str): print str When I

  • Dynamically set local variable in Python 2011-11-06

    This question already has an answer here: How can you dynamically create variables in Python via a while loop? 6 answers How do you dynamically set local variable in Python? (where the variable name is dynamic) UPDATE: I'm aware this isn't good pract

  • How to access the keys or values of Python GDB Value 2012-01-18

    I have a struct in GDB and want to run a script which examines this struct. In Python GDB you can easily access the struct via (gdb) python mystruct = gdb.parse_and_eval("mystruct") Now I got this variable called mystruct which is a GDB.Value object.

  • Why are local variables accessed faster than global variables in lua? 2012-02-03

    So I was reading Programing in Lua 2nd Ed and I came across this paragraph here: It is good programming style to use local variables whenever possible. Local variables help you avoid cluttering the global environment with unnecessary names. Moreover,

  • How can I access a shadowed global variable in C? 2009-03-06

    How can I access a shadowed global variable in C? In C++ I can use :: for the global namespace. --------------Solutions------------- If your file-scope variable is not static, then you can use a declaration that uses extern in a nested scope: int c;

  • determing access type of member variables of a class 2009-05-21

    Would following the table below be the best way of determining the access type of member variables of a class that I'm creating (sorry if this table is hard to see; it's the same table shown Access

  • Is Rails shared-nothing or can separate requests access the same runtime variables? 2009-06-22

    PHP runs in a shared-nothing environment, which in this context means that every web request is run in a clean environment. You can not access another request's data except through a separate persistence layer (filesystem, database, etc.). What about

  • Is modifying a class variable in python threadsafe? 2009-07-02

    I was reading this question (which you do not have to read because I will copy what is there... I just wanted to give show you my inspiration)... So, if I have a class that counts how many instances were created: class Foo(object): instance_count = 0

  • is there similar syntax to php's $$variable in python 2009-08-20

    is there similar syntax to php's $$variable in python? what I am actually trying is to load a model based on a value. for example, if the value is Song, I would like to import Song module. I know I can use if statements or lambada, but something simi

  • C++: How can a public static member function access private instance member variables? 2009-10-09

    I'm writing a C++ class to read input from a file into preallocated buffers called "chunks". I want the caller to be able to call a public static Chunk class method called GetNextFilledChunk(), which Grabs a Chunk from an inactive chunk pool Fills th

  • Gaining access to jndi environment variables within a Tomcat LifecycleListener 2009-12-16

    I'm using a LifecycleListener in tomcat to initialize some objects required by contexts in my web server. Within LifecycleListener I would like to have access to GlobalNamingResources Environment variables to keep the configuration for the server ins

  • Access a global static variable from another file in C 2009-12-29

    In C language, I want to access a global static variable outside the scope of the file. Let me know the best possible way to do it. One of the methods is to assign an extern global variable the value of static variable, In file a.c static int val = 1

Copyright (C), All Rights Reserved.

processed in 0.122 (s). 11 q(s)