Pep8 advises to always use cls
as the first argument of a class method definition.
Now suppose I want to use a class variable(in this case: cls.cartridge_state
) that can also be used in an instance method (in this case: __init__
). So for that I need to make the variable global(see code below). But instantiating FountainPen
generates the following runtime error:
self.cartridge_state = cls.cartridge_state
NameError: global name 'cls' is not defined
But then again when I change global cartridge_state
into global cls.cartridge_state
I get a syntaxError when i try to import the module.
class FountainPen(object):
cartridge_ink = "water-based"
@classmethod
def toggle_default_cartridge_state(cls):
i = 0
cartridge_states = ['non-empty','empty']
global cartridge_state
cls.cartridge_state = cartridge_states[i]
i += 1
def __init__(self):
self.cartridge_state = cls.cartridge_state
global number_of_refills
self.number_of_refills = 0
def write(self):
print Pen.write(self)
self.cartridge_state = "empty"
return self.cartridge_state
def refill(self):
self.cartridge_state = "non-empty"
self.number_of_refills += 1
How can I let the class variable cartridge_state
be pep8 compliant and make this code work without errors?