FAQ
How do you define a global variable in a class. I tried this with do
success:
class ClassName:
global_var = 1

def some_methos():
print global_var

This doesn't work. What am I doing wrong?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090717/0527713c/attachment.htm>

Search Discussions

  • Gabrielmonnerat at Jul 18, 2009 at 2:03 am

    Ronn Ross wrote:
    How do you define a global variable in a class. I tried this with do
    success:
    class ClassName:
    global_var = 1

    def some_methos():
    print global_var

    This doesn't work. What am I doing wrong?
    You need pass "self" to the function and "global_var" needs be called
    with self.

    class ClassName:
    global_var = 1

    def some_methos(self):
    print self.global_var


    Gabriel M. Monnerat
  • Rhodri James at Jul 18, 2009 at 1:17 pm

    On Sat, 18 Jul 2009 03:03:32 +0100, gabrielmonnerat wrote:

    Ronn Ross wrote:
    How do you define a global variable in a class. I tried this with do
    success:
    class ClassName:
    global_var = 1
    def some_methos():
    print global_var

    This doesn't work. What am I doing wrong?
    You need pass "self" to the function and "global_var" needs be called
    with self.

    class ClassName:
    global_var = 1
    def some_methos(self):
    print self.global_var
    If the OP really wants global_var to be global to the class, this
    approach will only work as long as he never assigns to self.global_var.

    The terminology is a bit confusing here. "Global variables" refers to
    variables which are global to an entire module, ones that you would
    use "global" to declare inside a function. Something like this:

    x = 5
    def set_x(y):
    global x
    x = y

    set_x(3)
    print x

    ...gives the result "3"

    The idea of defining a global variable in a class is a bit of a
    nonsense, since globals exist for the entire module. There are,
    however, variables that exist and are the same for every instance
    of a class, or "class attributes" as they are normally called. You
    use them either by assignment in the class definition, or in a
    method by prefixing them with the class name.

    class ClassName:
    global_var = 1
    def some_method(self):
    print ClassName.global_var
    ClassName.global_var = 2

    "Instance attributes", the ones prefixed by "self", are what get
    used for most purposes. These are separate for each different
    instance of the class.

    class ClassName:
    def __init__(self, val):
    self.var = val

    a = ClassName(1)
    b = ClassName(2)

    print a.var, b.var

    ...gives the result "1 2"

    The wrinkle is that if you read from an instance attribute that
    doesn't exist, Python will use a class attribute of the same name
    if there is one. This is often exploited for setting default
    values. Beware, though: the moment you assign, an instance
    attribute is created -- the underlying class attribute is *not*
    changed.

    class ClassName:
    global_var = 1
    def some_method(self):
    self.global_var = 2

    a = ClassName()
    b = ClassName()
    b.some_method()
    print a.global_var, b.global_var

    ...gives the result "1 2" again!

    --
    Rhodri James *-* Wildebeest Herder to the Masses
  • Albert Hopkins at Jul 18, 2009 at 2:13 am

    On Fri, 2009-07-17 at 21:42 -0400, Ronn Ross wrote:
    How do you define a global variable in a class.
    I bit of a mix-up with words here. A variable can be a class variable
    or a global variable (wrt the module).. not both.
    I tried this with do success:
    class ClassName:
    global_var = 1

    def some_methos():
    print global_var

    This doesn't work. What am I doing wrong?
    You could have posted the error message... Two things are wrong here.
    The first, if some_methos() is a method of ClassName then it should have
    at least one parameter, which is the instance of the class (i.e.
    "self"), so

    def some_methos(self):

    The second problem is that global_var is not local so you need to
    specify the scope. You can either use

    print ClassName.global_var

    or

    print self.global_var

    I'm not sure which one is better though I prefer the former because it
    makes it clearer to the reader that it's a class variable and not an
    instance variable.

    HTH,
    -a
  • Nohics nohics at Jul 18, 2009 at 2:40 am
    When defining your class methods, you *must* explicitly list self as the
    first argument for each method, including __init__. When you call a method
    of an ancestor class from within your class, you *must* include the
    selfargument. But when you call your class method from outside, you do
    not
    specify anything for the self argument; you skip it entirely, and
    Pythonautomatically adds the instance reference for you. I am aware
    that this is
    confusing at first; it's not really inconsistent, but it may appear
    inconsistent because it relies on a distinction (between bound and unbound
    methods) that you don't know about yet.

    So, you have to do:

    class ClassName:
    self.global_var = 1
    def some_methos(self):
    print self.global_var

    2009/7/18 Ronn Ross <ronn.ross at gmail.com>
    How do you define a global variable in a class. I tried this with do
    success:
    class ClassName:
    global_var = 1

    def some_methos():
    print global_var

    This doesn't work. What am I doing wrong?

    --
    http://mail.python.org/mailman/listinfo/python-list
    -------------- next part --------------
    An HTML attachment was scrubbed...
    URL: <http://mail.python.org/pipermail/python-list/attachments/20090718/472c1523/attachment.htm>
  • Gabrielmonnerat at Jul 18, 2009 at 3:06 am

    nohics nohics wrote:
    When defining your class methods, you /must/ explicitly list self as
    the first argument for each method, including __init__. When you call
    a method of an ancestor class from within your class, you /must/
    include the self argument. But when you call your class method from
    outside, you do not specify anything for the self argument; you skip
    it entirely, and Python automatically adds the instance reference for
    you. I am aware that this is confusing at first; it's not really
    inconsistent, but it may appear inconsistent because it relies on a
    distinction (between bound and unbound methods) that you don't know
    about yet.

    So, you have to do:

    class ClassName:
    self.global_var = 1
    self isn't exists in this context.
    class ClassName:
    ... self.global_var = 1
    ... def some_methods(self):
    ... print self.global_var
    ...
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "<stdin>", line 2, in ClassName
    NameError: name 'self' is not defined

    If you want a variable of instance you can use __init__
    class ClassName:
    ... def __init__(self):
    ... self.global_var = 1
    ... def some_methods(self):
    ... print self.global_var

    Now "global_var" is created when ClassName is instantiated
    ClassName.global_var
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    AttributeError: class ClassName has no attribute 'global_var'
    c = ClassName()
    c.global_var
    1
    def some_methos(self):
    print self.global_var

    2009/7/18 Ronn Ross <ronn.ross at gmail.com <mailto:ronn.ross at gmail.com>>

    How do you define a global variable in a class. I tried this with
    do success:
    class ClassName:
    global_var = 1

    def some_methos():
    print global_var

    This doesn't work. What am I doing wrong?

    --
    http://mail.python.org/mailman/listinfo/python-list
  • Gabriel Genellina at Jul 18, 2009 at 3:34 am
    En Fri, 17 Jul 2009 22:42:43 -0300, Ronn Ross <ronn.ross at gmail.com>
    escribi?:
    How do you define a global variable in a class. I tried this with do
    success:
    class ClassName:
    global_var = 1

    def some_method(self):
    print global_var

    This doesn't work. What am I doing wrong?
    [some typos fixed]

    In Python, a "variable" is just a name in a namespace that references
    another object.
    There are five possible namespaces here:

    - The local namespace, that is, the namespace inside some_method. All
    assigned-to names that appear inside the function (there is none in this
    case) are in the local namespace. But you're not interested on these local
    names, I presume, because you said "global"

    - The global namespace: the namespace of the module containing the code
    (NOT a "super-global" namespace shared by all modules). Names in this
    namespace are "global" in the sense that all code in the same module can
    reference them. But they're not restricted to any class, as you requested.
    To use a global name in an expression, just write it. To assign a new
    value to a global name, you must use the "global" statement if you're
    inside a function (else, it's considered a local name, see above).

    - The built-in namespace: like a super-global namespace, it is searched
    last when looking for an unqualified name; by example, the "len" function.
    For most purposes, you should consider the built-in namespace read-only.

    - The instance namespace: each object has its own namespace; you access
    its names using dotted attributes: obj.name -- or self.attribute when
    inside a method. The instance namespace is not determined by the object
    type or class; any object may contain any attribute name (in general).

    - The class namespace: classes may contain attributes too (like any other
    object, because classes are objects too). In your code above, you may use
    ClassName.global_var to refer to such class attribute. To resolve a dotted
    attribute name, Python searches the instance first -- and if no match is
    found, then the class namespace is searched too: this way, class
    attributes effectively are "default values" for instance attributes. Since
    all existing instances of a certain class share the same class, this is
    like a "shared attribute" between all instances (like "static members" in
    other languages). Inside some_method above, you may use self.global_var or
    ClassName.global_var -- but once you *assign* something to the instance
    attribute (self.global_var = xxx), the class attribute is shadowed and you
    may reference it using ClassName.global_var only.

    --
    Gabriel Genellina

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
grouppython-list @
categoriespython
postedJul 18, '09 at 1:42a
activeJul 18, '09 at 1:17p
posts7
users6
websitepython.org

People

Translate

site design / logo © 2022 Grokbase