Skip to content

Learning Python: Day 23

Chapter 9 – Classes

  • object-oriented programming (OOP) – is one of the most effective approaches to writing software
  • classes – used in object-oriented programming to represent real-world things and situations
  • objects – created based on these classes, general behavior defined when class is written
  • instantiation – making an object from a class
  • instances – created for classes to store information, with defined actions that can be taken
  • object-oriented programming will help you see the world as a programmer does

Creating and using a class

  • classes can model almost anything
  • For example, a simple class, Dog, can represent any dog, can contain two pieces of information (name and age) and two behaviors (sit and roll over)

Creating the dog class

  • each instance created from the Dog class will store a name and an age, and will give each dog the ability to sit() and roll_over()

dog.py

class Dog:

….”””A simple attempt to model a dog.”””

….def_init_(self, name, age):

……..”””Initialize name and age attributes.”””

……..self.name = name

……..self.age = age

….def sit(self):

……..”””Simulate a dog sitting in response to a command.”””

……..print(f”{self.name} is now sitting.”)

….def roll_over(self):

……..”””Simulate rolling over in response to a command.”””

……..print(f”{self.name} rolled over!”)

  • first defined a class called Dog (capital names refer to classes in Python by default)
  • no parentheses in the class definition because the class is created from scratch
  • then write a docstring describing what this class does

End of study session.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *