Python Programming/Classes
This lesson introduces Python classes.
Objectives and Skills
[edit | edit source]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 | edit source]- Wikipedia: Object-oriented programming
- Sthurlow: Python Classes
- Jess Hamrick: An Introduction to Classes and Inheritance (in Python)
Multimedia
[edit | edit source]- YouTube: Python Classes and Objects
- YouTube: Python init
- YouTube: Python Class vs. Instance Variables
- YouTube: Python Inheritance
- YouTube: Python Classes and Objects Playlist
Examples
[edit | edit source]Class Definition
[edit | edit source]Classes are defined using the syntax:[2]
class ClassName:
<statements>
Class Instantiation
[edit | edit source]Classes are instantiated using the syntax:[3]
variable = ClassName()
Class Attributes
[edit | edit source]Class attributes (variables) are defined using the syntax:[4]
class ClassName:
attribute = value
Class Methods
[edit | edit source]Class methods (functions) are defined using the syntax:[5]
class ClassName:
def function(self):
<statements>
Class Initialization
[edit | edit source]Class attributes may be initialized during instantiation using the __init__() method.[6]
class ClassName:
def __init__(self, attribute[, attribute, ...]):
<statements>
Class Example
[edit | edit source]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 | edit source]Subclasses are defined using the syntax:[7]
class DerivedClassName(BaseClassName):
<statements>
Inheritance Example
[edit | edit source]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 | edit source]Tutorials
[edit | edit source]- Complete one or more of the following tutorials:
- LearnPython
- TutorialsPoint
- Codecademy
- Wikiversity
- Wikibooks
Practice
[edit | edit source]- 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.
- 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.
- 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.
- 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 | edit source]Class Concepts
[edit | edit source]- 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 | edit source]- 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 | edit source]- 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 | edit source]-
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.
-
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".
-
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).
-
Objects are _____.Objects are instances of classes.
-
Class variables belong to _____.Class variables belong to the class as a whole; there is only one copy of each one.
-
Instance variables or attributes belong to _____.Instance variables or attributes belong to individual objects; every object has its own copy of each one.
-
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.
-
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.
-
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.
-
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.
-
Objects are created by calling _____.Objects are created by calling a special type of method in the class known as a constructor.
-
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.
-
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.
-
Subclasses can override _____.Subclasses can override the methods defined by superclasses.
-
Classes are defined using the syntax:Classes are defined using the syntax:
class ClassName:
<statements>
-
Classes are instantiated using the syntax:{{{2}}}
-
Class attributes (variables) are defined using the syntax:{{{2}}}
-
Class methods (functions) are defined using the syntax:Class methods (functions) are defined using the syntax:
class ClassName:
def function(self):
<statements>
-
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>
-
Subclasses are defined using the syntax:Subclasses are defined using the syntax:
class DerivedClassName(BaseClassName):
<statements>
Assessments
[edit | edit source]- Flashcards: Quizlet: Python Classes
- Quiz: Quizlet: Python Classes
See Also
[edit | edit source]- Python.org: Classes
- PythonBasics: classes and oop tutorial
- SoloLearn: Python
- Open Book Project: Python 3 - Classes and Objects
- Stéphane Ducasse - Free Online Books: Designing Object Systems
References
[edit | edit source]- ↑ Vskills: Certified Python Developer
- ↑ Python.org: Classes
- ↑ Python.org: Classes
- ↑ Python.org: Classes
- ↑ Python.org: Classes
- ↑ Python.org: Classes
- ↑ Python.org: Classes
- ↑ Wikipedia: Object-oriented programming
- ↑ Wikipedia: Object-oriented programming
- ↑ Wikipedia: Object-oriented programming
- ↑ Wikipedia: Object-oriented programming
- ↑ Wikipedia: Object-oriented programming
- ↑ Wikipedia: Object-oriented programming
- ↑ Wikipedia: Object-oriented programming
- ↑ Wikipedia: Object-oriented programming
- ↑ Wikipedia: Object-oriented programming
- ↑ Wikipedia: Object-oriented programming
- ↑ Wikipedia: Object-oriented programming
- ↑ Wikipedia: Object-oriented programming
- ↑ Wikipedia: Object-oriented programming
- ↑ Wikipedia: Object-oriented programming
- ↑ Python.org: Classes
- ↑ Python.org: Classes
- ↑ Python.org: Classes
- ↑ Python.org: Classes
- ↑ Python.org: Classes
- ↑ Python.org: Classes
- ↑ Wikipedia: Field (computer science)
- ↑ Wikipedia: Class (computer programming)
- ↑ Wikipedia: Constructor (object-oriented programming)
- ↑ Wikipedia: Inheritance (object-oriented programming)
- ↑ Wikipedia: Instance (computer science)
- ↑ Wikipedia: Instance (computer science)
- ↑ Wikipedia: Method (computer programming)
- ↑ Wikipedia: Object (computer science)
- ↑ Wikipedia: Inheritance (object-oriented programming)