![]() |
Class variables - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Class variables (/thread-27368.html) |
Class variables - menator01 - Jun-04-2020 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 RE: Class variables - Clunk_Head - Jun-04-2020 (Jun-04-2020, 12:53 PM)menator01 Wrote: Given the scenario 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 RE: Class variables - Yoriz - Jun-04-2020 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()
|