How to access variables from class constructor to the class functions?
Code:
class evol:
k = 0
m = 0
def __init__(self, file1):
InFile = open(file1, 'rb')
InFile = csv.reader(InFile, delimiter='\t')
for rec in InFile:
self.k += int(rec[0])
def method1():
print k
I get the error, NameError: global name 'k' is not defined
def method(self): print self.k. You may be familiar with other programming languages that use thethiskeyword, its basically that.selfis just the convention to pass the reference of itself. You could also dodef method(self): print evol.k. In python class variables can be accessed like that. In either case, themethod1needs paramselfso that it knows its abound methodrather than astaticor some other functionclass variablewill remain that value for the class and can be modified via the class. Since it doesn't haveselfas a reference as inself.k = 12under__init__, it doesn't know who it's referring to. That's why it's always better to initialize variables under__init__