Classes

Object-oriented programming (OOP)

Object-oriented programming is a method of programing that bundles behaviors and properties into objects. OOP is supported by Python. A class is a blueprint for an object. In this section we will show how to define a class, give the class attributes and methods, and use class inheritance.

A class has a form like this:

..code:

class ClassName:
  # Class attribute
  (statement)

  # instance attributes
  def __init__(self, name, age):
      self.attr1 = value
  .
  .
  .
  # instance methods
  def method1(self, para1):
      body
  .
  .
  .

A Class with Attributes and Methods

For our example we will create object that represent a person. Each of these objects wiil have two attributes and two methods.

It is standard practice to use a capital letter for naming a class.

We define our properties and set the initial state by defining the .__init__( )

class Person:
    # Class attribute
    species = 'human'

    def __str__(self):
        return f"{self.name} is a {self}."

    # instance attributes
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # instance methods
    def greets(self, phrase):
        return f'{self.name} says, {phrase}.'

    def responds(self, phrase):
        return f'{self.name}, replies {phrase}.'

Class Inheritance

class Female(Person):
    gender = 'female'
    likes = 'movies'

    def responds(self, phrase='get lost'):
    return super().responds(phrase)

class Male(Person):
    gender = 'male'
    likes = 'sports'

    def greets(self, phrase='what\'s your sign'):
        return super().greets(phrase)

Class Customization

A class in Python can implement certain operations by defining methods with special method names.

  • __repr__

  • __str__

  • define an ordering by defining __gt__ and __ge__

__repr__: Called by the repr() built-in function to compute the “official” string representation of an object. __str__: Called by str(object) and the built-in functions format() and print() to compute the “informal” or nicely printable string representation of an object.

class Order:
    description = 'Ordering'

    def __init__(self, position):
        self.position = position

    def __gt__(self, other):
        value = self.position < other.position
        return value

    def __ge__(self, other):
        value = self.position <= other.position
        return value

    def __repr__(self):
        return f'<Order({self.position})>'

    def __str__(self):
        return f'\"Order({self.position})\"'