So I am recently new to Python, but I seem to be able to program some stuff and get it working. However I've been trying to expand my knowledge of how things work in the language, and putting this simple file together confuses me.
class TestA:def __init__(self):self.varNum = 3def printNum(self):print(self.varNum)class TestB:varNum = 0def __init__(self):varNum = 3def printNum(self):global varNumprint(varNum)a = TestA()
a.printNum()b = TestB()
b.printNum()
The code to TestA
prints 3 to the screen properly. However the code for TestB
instead gives me a NameError
stating that: 'varNum' is not defined
. And I get that error whether i have the global varNum
line there or not.
I suppose what confuses me, is I see the __init__
function as a class constructor. And when I have programmed with languages such as Java or C# I've declared global variables outside of the constructor so that their scope is the whole class. Is that not a thing in Python? The code I've written I just kind of tagged self.
onto everything because I was just trying to get some stuff put together quickly, but I am trying to figure more out about the language now. Is self.
the only way in Python to make class scope variables? Or are there other ways?
Thanks for your time :)