Python Forum

Full Version: Class variables
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Given the scenario
class SomeClass:
    myvar = 0
    def __init__(self):
        do stuff here
    def func(self):
        do stuff here
        myvar += 1
        print(myvar)
Would not myvar be a global for the class?
I'm getting that it has not been assigned in the function.
Input much appreciated
(Jun-04-2020, 12:53 PM)menator01 Wrote: [ -> ]Given the scenario
class SomeClass:
    myvar = 0
    def __init__(self):
        do stuff here
    def func(self):
        do stuff here
        myvar += 1
        print(myvar)
Would not myvar be a global for the class?
I'm getting that it has not been assigned in the function.
Input much appreciated

I'd say that you haven't received a reply because your question obfuscates your problem. You don't have an example of usage or any error code. That aside I have a bit of advise on your problem.

Class variables are accessed the same way that instance variables are accessed, that is by way of an instance.

class SomeClass:
    myvar = 0
    def __init__(self):
        do stuff here
    def func(self):
        do stuff here
        myvar += 1
        print(myvar)

my_instance = SomeClass()
print(my_instance.myvar) 
#Unlike some other languages class variables in python are not accessed by the class name
Here is an example of accessing the class variable and the instance variable
class SomeClass:
    myvar = 0

    def __init__(self):
        self.myvar = 10

    def increase_class_variable(self):
        SomeClass.myvar += 1
        print(f'Shared class variable: {SomeClass.myvar}')

    def increase_instance_variable(self):
        self.myvar += 1
        print(f'Instance variable: {self.myvar}')


instance1 = SomeClass()
instance2 = SomeClass()
instance1.increase_class_variable()
instance1.increase_class_variable()
instance2.increase_class_variable()
instance1.increase_instance_variable()
instance1.increase_instance_variable()
instance2.increase_instance_variable()
Output:
Shared class variable: 1 Shared class variable: 2 Shared class variable: 3 Instance variable: 11 Instance variable: 12 Instance variable: 11