The answer by robert is probably the easiest way to do what your want. Here is another:
class class1():
a,b = somevalues, somevalues
@staticmethod
def func1():
do something
func2(class1.a, class1.b)
class1.func1()
The reason this works and your way doesn't work has to do with the way Python treats functions and classes.
The body of a function is not executed until it is called the first time. So when you have:
def func1():
func1.a = somevalue
...you cannot access func1.a
until func1
has been called at least once, as you have already discovered.
However, for classes, the body of the class runs when the code is compiled. So that when you do:
class example:
a = somevalue
...you are able to access example.a
immediately.
EDIT:
Answering the question in the comments: access func1
, a
, or b
as shown above using the class itself (in Python, classes ARE objects, just like any other object):
class1.a
class1.func1()
You could also make a shortcut for yourself:
func1 = class1.func1
func1()
Another way to do things- so that you could have different versions of a
and b
- be to make a
and b
instance attributes instead of class attributes.
class class1:
def __init__(self, a, b):
self.a, self.b = a, b
@staticmethod
def func1():
dosomething
obj1 = class1(somevalue1A, somevalue1B)
obj2 = class1(somevalue2A, somevalue2B)
func2(obj1.a, obj1.b)
func2(obj2.a, obj2.b)
obj1.func1()
obj2.func1()
class1.func1()
The last three lines all call the same function, because obj1.func1
, obj2.func1
, and class1.func1
all point to the same method of class1
. Note that the reason you can call func1
from both the class (class1
) and the instances (obj1
, obj2
) of the class is that func1
is a static method.