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.r...@gmail.com <mailto:ronn.r...@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
--
http://mail.python.org/mailman/listinfo/python-list