Data Analysis

State data within a Python Class definition

From my procedural language days, state data was easier for me to understand than in some OOP languages. It took me a while, for instance, but I finally got the syntax correct below for creating a local state variable within a Python class here: [the solution was to create the var “self.count” with the _init_ method below… not as ‘count’ but as ‘self.count’ and referenced as such elsewhere]

class Classy(object):

# PAB: note that I added self.count and referenced it elsewhere in the class methods.

def __init__(self):

     self.count = 0



def addItem(self, item):

# Python's version of a CASE statement:

    if item == "tophat":

        self.count += 2

    elif item == "bowtie":

        self.count += 4

    elif item == "monocle":

        self.count += 5



def getClassiness(self):

    return (self.count)

# You’ll get the following error if you don’t add (self) to all of your Class def methods:

" ... takes no arguments (1 given)"