Python Classes Quick Reference

Table Of Contents

  1. Simple Class
  2. Member Variables
  3. Constructor
  4. String Representation

1. Simple Class


In [2]:
# simple definition.  All member functions must take parameter self (this in c++)

class Car:
    def drive(self):
        print('vroom vroom...')
        
miata = Car()
miata.drive()


vroom vroom...

2. Member Variables


In [3]:
# declare variable

class Car:
    make = 'unknown car type'
    def drive(self):
        print('driving my %s vroom vroom...' % self.make)

miata = Car()
miata.make = 'miata'
miata.drive()


driving my miata vroom vroom...

3. Constructor


In [4]:
# constructor syntax

class Car:
    make = 'unknown car type'
    def __init__(self,make):
        self.make=make
    def drive(self):
        print('driving my %s vroom vroom...' % self.make)

maiata=Car('miata')
miata.drive()
miata.make


driving my miata vroom vroom...
Out[4]:
'miata'

4. String Representation


In [5]:
#used to sort objects that dont natively support comparison
class User:
    def __init__(self, user_id):
        self.user_id = user_id
    def __repr__(self):
        return 'User({})'.format(self.user_id)
        
User(23)


Out[5]:
User(23)

In [ ]: