Data Science and Python


 Python

Object-Oriented Programming


Like many languages, Python allows you to define classes that encapsulate data and the functions that operate on them. We’ll use them sometimes to make our code cleaner and simpler. It’s probably simplest to explain them by constructing a heavily annotated example.


Here we’ll construct a class representing a “counting clicker,” the sort that is used at the door to track how many people have shown up for the “advanced topics in data science” meetup.


It maintains a count, can be clicked to increment the count, allows you to read_count, and can be reset back to zero. (In real life one of these rolls over from 9999 to 0000, but we won’t bother with that.)
To define a class, you use the class keyword and a PascalCase name:
class CountingClicker:
    """A class can/should have a docstring, just like a function"""

A class contains zero or more member functions. By convention, each takes a first parameter, self, that refers to the particular class instance.


Normally, a class has a constructor, named __init__. It takes whatever parameters you need to construct an instance of your class and does whatever setup you need:
    def __init__(self, count = 0):
        self.count = count

Although the constructor has a funny name, we construct instances of the clicker using just the class name:
clicker1 = CountingClicker()           # initialized to 0
clicker2 = CountingClicker(100)        # starts with count=100
clicker3 = CountingClicker(count=100)  # more explicit way of doing the same


Notice that the __init__ method name starts and ends with double underscores. These “magic” methods are sometimes called “dunder” methods (double-UNDERscore, get it?) and represent “special” behaviors.


Popular posts from this blog

Machine Learning

Robotics and Skills

Artificial Intelligence