Python Programming/Classes

From Wikiversity
Jump to: navigation, search

This lesson introduces Python classes.

Objectives and Skills[edit]

Objectives and skills for this lesson include:[1]

  • Object Oriented Programming
    • The self
    • Classes
    • Object Methods and the __init__ method
    • Class And Object Variables
    • Inheritance

Readings[edit]

  1. Wikipedia: Object-oriented programming
  2. Sthurlow: Python Classes
  3. Jess Hamrick: An Introduction to Classes and Inheritance (in Python)

Multimedia[edit]

  1. YouTube: Python Classes and Objects
  2. YouTube: Python init
  3. YouTube: Python Class vs. Instance Variables
  4. YouTube: Python Inheritance

Examples[edit]

Class Definition[edit]

Classes are defined using the syntax:[2]

class ClassName:
    <statements>

Class Instantiation[edit]

Classes are instantiated using the syntax:[3]

variable = ClassName()

Class Attributes[edit]

Class attributes (variables) are defined using the syntax:[4]

class ClassName:
    attribute = value

Class Methods[edit]

Class methods (functions) are defined using the syntax:[5]

class ClassName:
    def function(self):
        <statements>

Class Initialization[edit]

Class attributes may be initialized during instantiation using the __init__() method.[6]

class ClassName:
    def __init__(self, attribute[, attribute, ...]):
        <statements>

Class Example[edit]

The following example creates a class named Shape with an attribute named sides and a method named perimeter. Three instances of the class are created, one each for a triangle, rectangle, and square. The attribute value and method result are printed for each shape.

class Shape(object):
    sides = None

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

    def perimeter(self):
        perimeter = 0
        for side in self.sides:
            perimeter += side
        return perimeter

triangle = Shape([3, 4, 5])
print("triangle sides:", triangle.sides)
print("triangle perimeter:", triangle.perimeter())

rectangle = Shape([4, 2, 4, 2])
print("rectangle sides:", rectangle.sides)
print("rectangle perimeter:", rectangle.perimeter())

square = Shape([2, 2, 2, 2])
print("square sides:", square.sides)
print("square perimeter:", square.perimeter())

Output:

triangle sides: [3, 4, 5]
triangle perimeter: 12
rectangle sides: [4, 2, 4, 2]
rectangle perimeter: 12
square sides: [2, 2, 2, 2]
square perimeter: 8

Inheritance[edit]

Subclasses are defined using the syntax:[7]

class DerivedClassName(BaseClassName):
    <statements>

Inheritance Example[edit]

The following example creates a class named Shape with an attribute named sides and a method named perimeter. Three subclasses are created named Triangle, Rectangle, and Square. An instance of each subclass is created, and the attribute value and method result are printed for each shape.

class Shape(object):
    sides = None

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

    def perimeter(self):
        perimeter = 0
        for side in self.sides:
            perimeter += side
        return perimeter

class Triangle(Shape):
    def __init__(self, side1, side2, side3):
        self.sides = [side1, side2, side3]

class Rectangle(Shape):
    def __init__(self, length, width):
        self.sides = [length, width, length, width]

class Square(Shape):
    def __init__(self, side):
        self.sides = [side, side, side, side]

triangle = Triangle(3, 4, 5)
print("triangle sides:", triangle.sides)
print("triangle perimeter:", triangle.perimeter())

rectangle = Rectangle(4, 2)
print("rectangle sides:", rectangle.sides)
print("rectangle perimeter:", rectangle.perimeter())

square = Square(2)
print("square sides:", square.sides)
print("square perimeter:", square.perimeter())

Output:

triangle sides: [3, 4, 5]
triangle perimeter: 12
rectangle sides: [4, 2, 4, 2]
rectangle perimeter: 12
square sides: [2, 2, 2, 2]
square perimeter: 8

Activities[edit]

Tutorials[edit]

  1. Complete one or more of the following tutorials:

Practice[edit]

  1. Create a Python program that asks the user how old they are in years. Then ask the user if they would like to know how old they are in months, days, hours, or seconds. Use a condition statement to determine their selection, and display their approximate age in the selected timeframe. Perform all calculations using an AgeConverter class that accepts the age in years during initialization and has separate methods that calculate and return the age in months, days, hours, and seconds. Include data validation in the class and error handling in the main program.
  2. Review MathsIsFun: Conversion of Temperature. Create a Python program that asks the user if they would like to convert Fahrenheit to Celsius or Celsius to Fahrenheit. Use a condition statement to determine their selection and then gather the appropriate input. Perform all calculations using a TemperatureConverter class that accepts the temperature during initialization and has separate methods that calculate and return the temperature in Celsius and Fahrenheit. Include data validation in the class and error handling in the main program.
  3. Review MathsIsFun: Area of Plane Shapes. Create a Python program that asks the user what shape they would like to calculate the area for. Use a condition statement to determine their selection and then gather the appropriate input. Perform all area calculations using a Shape main class and subclasses for each selected shape type. Include data validation in the class and error handling in the main program.
  4. Create a Python program that contains a dictionary of names and phone numbers. Use a class to contain and maintain the dictionary, and use methods to add, update, remove, and search for names and numbers. Include data validation in the class and error handling in the main program.

Lesson Summary[edit]

Class Concepts[edit]

  • Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which may contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods.[8]
  • A feature of objects is that an object's procedures can access and often modify the data fields of the object with which they are associated through a notion of "this" or "self".[9]
  • Classes define the data format and available procedures for a given type of object and may also contain data and procedures (known as class attributes and methods).[10]
  • Objects are instances of classes.[11]
  • Class variables belong to the class as a whole; there is only one copy of each one.[12]
  • Instance variables or attributes belong to individual objects; every object has its own copy of each one.[13]
  • Class methods belong to the class as a whole and have access only to class variables and inputs from the procedure call.[14]
  • Instance methods belong to individual objects, and have access to instance variables for the specific object they are called on, inputs, and class variables.[15]
  • Classes have a unique namespace so code in one class will not be accidentally confused with the same procedure or variable name in another class.[16]
  • Classes provide a layer of abstraction which can be used to separate internal from external code. External code can use an object by calling a specific instance method with a certain set of input parameters, read an instance variable, or write to an instance variable.[17]
  • Objects are created by calling a special type of method in the class known as a constructor.[18]
  • A program may create many instances of the same class as it runs, which operate independently. This is an easy way for the same procedures to be used on different sets of data.[19]
  • Inheritance allows classes to be arranged in a hierarchy that represents "is-a-type-of" relationships. All data and methods available to the parent class also appear in the child class with the same names.[20]
  • Subclasses can override the methods defined by superclasses.[21]

Python Classes[edit]

  • Classes are defined using the syntax:[22]

    class ClassName:
        <statements>

  • Classes are instantiated using the syntax:[23]

    variable = ClassName()

  • Class attributes (variables) are defined using the syntax:[24]

    class ClassName:
        attribute = value

  • Class methods (functions) are defined using the syntax:[25]
        class ClassName:
            def function(self):
                <statements>
  • Class attributes may be initialized during instantiation using the __init__() method.[26]
        class ClassName:
            def __init__(self, attribute[, attribute, ...]):
                <statements>
  • Subclasses are defined using the syntax:[27]
        class DerivedClassName(BaseClassName):
            <statements>

Key Terms[edit]

attribute
Data encapsulated within a class or object.[28]
class
An extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods).[29]
constructor
A special type of procedure called to create an object which prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.[30]
inheritance
When an object or class is based on another object or class using the same implementation to maintain the same behavior.[31]
instance
A concrete occurrence of an object.[32]
instantiate
To create an occurrence of an object, typically by calling its constructor.[33]
method
A procedure associated with an object.[34]
object
A particular instance of a class.[35]
subclass
A modular, derivative class that inherits one or more language entities from one or more other classes (called superclasses, base classes, or parent classes).[36]

Review Questions[edit]

Enable JavaScript to hide answers.
Click on a question to see the answer.
  1. Object-oriented programming (OOP) is _____.
    Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which may contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods.
  2. A feature of objects is _____.
    A feature of objects is that an object's procedures can access and often modify the data fields of the object with which they are associated through a notion of "this" or "self".
  3. Classes define _____.
    Classes define the data format and available procedures for a given type of object and may also contain data and procedures (known as class attributes and methods).
  4. Objects are _____.
    Objects are instances of classes.
  5. Class variables belong to _____.
    Class variables belong to the class as a whole; there is only one copy of each one.
  6. Instance variables or attributes belong to _____.
    Instance variables or attributes belong to individual objects; every object has its own copy of each one.
  7. Class methods belong to _____.
    Class methods belong to the class as a whole and have access only to class variables and inputs from the procedure call.
  8. Instance methods belong to _____.
    Instance methods belong to individual objects, and have access to instance variables for the specific object they are called on, inputs, and class variables.
  9. Classes have a unique _____.
    Classes have a unique namespace so code in one class will not be accidentally confused with the same procedure or variable name in another class.
  10. Classes provide a layer of abstraction which _____.
    Classes provide a layer of abstraction which can be used to separate internal from external code. External code can use an object by calling a specific instance method with a certain set of input parameters, read an instance variable, or write to an instance variable.
  11. Objects are created by calling _____.
    Objects are created by calling a special type of method in the class known as a constructor.
  12. A program may create many _____ of the same class as it runs, which operate independently. This is an easy way for the same procedures to be used on different sets of data.
    A program may create many instances of the same class as it runs, which operate independently. This is an easy way for the same procedures to be used on different sets of data.
  13. Inheritance allows classes to _____.
    Inheritance allows classes to be arranged in a hierarchy that represents "is-a-type-of" relationships. All data and methods available to the parent class also appear in the child class with the same names.
  14. Subclasses can override _____.
    Subclasses can override the methods defined by superclasses.
  15. Classes are defined using the syntax:
    Classes are defined using the syntax:
        class ClassName:
            <statements>
  16. Classes are instantiated using the syntax:
    {{{2}}}
  17. Class attributes (variables) are defined using the syntax:
    {{{2}}}
  18. Class methods (functions) are defined using the syntax:
    Class methods (functions) are defined using the syntax:
        class ClassName:
            def function(self):
                <statements>
  19. Class attributes may be initialized during instantiation using the ____ method.
    Class attributes may be initialized during instantiation using the __init__() method.
        class ClassName:
            def __init__(self, attribute[, attribute, ...]):
                <statements>
  20. Subclasses are defined using the syntax:
    Subclasses are defined using the syntax:
        class DerivedClassName(BaseClassName):
            <statements>

Assessments[edit]

See Also[edit]

References[edit]