Classes, Constructors, and Attributes

my_variable = "My value"
my_variable = [10, 20, 19, 5, 0]

Object Oriented Programming

  • Group multiple variables together in a single record
  • Associate functions (methods) to work with a group of data (object)
  • Use inheritance to extend a base set of code with new functionality

Using Classes and Objects to Group Data

name = "Link"
outfit = "Green"
max_hit_points = 50
current_hit_points = 50
armor_amount = 6
max_speed = 10
def display_character(name, outfit, max_hit_points, current_hit_points, armor, max_speed):
    print(name, outfit, max_hit_points, current_hit_points)

Defining Classes

class Character:
    """
    This is a class that represents the player character.
    """

Defining the

__init__

function

class Character:
    """
    This is a class that represents the player character.
    """
    def __init__(self):
        """ This is a method that sets up the variables in the object. """

Defining Class Attributes

class Character:
    """
    This is a class that represents the player character.
    """
    def __init__(self):
        """ This is a method that sets up the variables in the object. """
        self.name = ""
        self.outfit = ""
        self.max_hit_points = 0
        self.current_hit_points = 0
        self.armor_amount = 0
        self.max_speed = 0
class Address:
    """ Hold all the fields for a mailing address. """
    def __init__(self):
        """ Set up the address fields. """
        self.name = ""
        self.line1 = ""
        self.line2 = ""
        self.city = ""
        self.state = ""
        self.zip = ""

Creating Objects

def main():
    # Create an address
    home_address = Address()
def main():
    # Create an address
    home_address = Address()

    # Set the fields in the address
    home_address.name = "John Smith"
    home_address.line1 = "701 N. C Street"
    home_address.line2 = "Carver Science Building"
    home_address.city = "Indianola"
    home_address.state = "IA"
    home_address.zip = "50125"
def main():
    # Create an address
    home_address = Address()

    # Set the fields in the address
    home_address.name = "John Smith"
    home_address.line1 = "701 N. C Street"
    home_address.line2 = "Carver Science Building"
    home_address.city = "Indianola"
    home_address.state = "IA"
    home_address.zip = "50125"
    
    # Create another address
    vacation_home_address = Address()

    # Set the fields in the address
    vacation_home_address.name = "John Smith"
    vacation_home_address.line1 = "1122 Main Street"
    vacation_home_address.line2 = ""
    vacation_home_address.city = "Panama City Beach"
    vacation_home_address.state = "FL"
    vacation_home_address.zip = "32407"

    print("The client's main home is in " + home_address.city)
    print("His vacation home is in " + vacation_home_address.city)    

Common Mistakes

Creating Objects

class Address:
    def __init__(self):
        self.name = ""
        self.line1 = ""
        self.line2 = ""
        self.city = ""
        self.state = ""
        self.zip = ""

def main():
    # ERROR - Forgot the parentheses after Address
    my_address = Address
class Address:
    def __init__(self):
        self.name = ""
        self.line1 = ""
        self.line2 = ""
        self.city = ""
        self.state = ""
        self.zip = ""

def main():
    # Create an address
    my_address = Address()

    # Alert! This does not set the address's name!
    name = "Dr. Smith"

    # This doesn't set the name for the address either
    Address.name = "Dr. Smith"

    # This runs, creates a new attribute but with the wrong name.
    my_address.naem = "Dr. Smith"

    # This does work:
    my_address.name = "Dr. Smith"

main()

Using Objects in Functions

def print_address(address):
    """ Print an address to the screen """

    print(address.name)
    # If there is a line1 in the address, print it
    if len(address.line1) > 0:
        print(address.line1)
    # If there is a line2 in the address, print it
    if len(address.line2) > 0:
        print( address.line2 )
    print(address.city + ", " + address.state + " " + address.zip)


def main():
    # ... code for creating home_address and vacation_home_address
    # goes here.
    print_address(home_address)
    print()
    print_address(vacation_home_address)


main()

Customizing the Constructor

class Dog():
    def __init__(self):
        """ Constructor """

        self.name = ""


def main():
    my_dog = Dog()


main()
class Dog():
    def __init__(self):
        """ Constructor. Called when creating an object of this type. """
        self.name = ""

        print("A new dog is born!")


def main():
    # This creates the dog
    my_dog = Dog()
class Dog():

    def __init__(self, new_name):

        """ Constructor. Called when creating an object of this type. """

        self.name = new_name

        print("A new dog is born!")


def main():
    # This creates the dog
    my_dog = Dog()


main()
class Dog():
    def __init__(self, new_name):
        """ Constructor. Called when creating an object of this type. """
        self.name = new_name
        print("A new dog is born!")


def main():
    # This creates the dog

    my_dog = Dog("Fluffy")



main()
class Dog():

    def __init__(self, name):

        """ Constructor. Called when creating an object of this type. """

        self.name = name

        print("A new dog is born!")


def main():
    # This creates the dog
    my_dog = Dog("Fluffy")


main()

Typing Attributes

class Person:
    def __init__(self):
        self.name: str = "A"


mary = Person()
mary.name = 22

Data Classes

class Address:
    def __init__(self,
                 name: str = "",
                 line1: str = "",
                 line2: str = "",
                 city: str = "",
                 state: str = "",
                 zip_code: str = ""
                 ):
        self.name: str = name
        self.line1: str = line1
        self.line2: str = line2
        self.city: str = city
        self.state: str = state
        self.zip_code: str = zip_code
@dataclass
class Address:
    name: str = ""
    line1: str = ""
    line2: str = ""
    city: str = ""
    state: str = ""
    zip_code: str = ""

Static Variables

Class Attributes

  • Remember - Class attributes are variables that are part of a class.
  • Instance variables are different for each instance of an object.
  • Static variables are the same, no matter which object we reference. The data is shared between instances.
class Cat:

    population = 0


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

        Cat.population += 1


def main():
    cat1 = Cat("Pat")
    cat2 = Cat("Pepper")
    cat3 = Cat("Pouncy")


    print("The cat population is:", Cat.population)


main()
class Cat:

    population = 0


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

        Cat.population += 1


def main():
    cat1 = Cat("Pat")
    cat2 = Cat("Pepper")
    cat3 = Cat("Pouncy")


    print("The cat population is:", Cat.population)
    print("The cat population is:", cat1.population)


main()
class Cat:

    population = 0


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

        Cat.population += 1


def main():
    cat1 = Cat("Pat")
    cat2 = Cat("Pepper")
    cat3 = Cat("Pouncy")

    Cat.population = 4
    print("The cat population is:", Cat.population)
    print("The cat population is:", cat2.population)
    print("The cat population is:", cat1.population)


main()
class Cat:

    population = 0


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

        Cat.population += 1


def main():
    cat1 = Cat("Pat")
    cat2 = Cat("Pepper")
    cat3 = Cat("Pouncy")

    Cat.population = 4
    cat3.population = 5
    print("The cat population is:", Cat.population)
    print("The cat population is:", cat1.population)
    print("The cat population is:", cat2.population)
    print("The cat population is:", cat3.population)


main()

Review

Bundle data into a class

  • Class attributes
  • Instance variables
  • Fields

__init__

  • "Magic Method" called when object is created
  • Sets up instance variables
  • Assign default values

Refer to instance variables

  • Inside the class: self.name
  • Outside the class: customer.name

Classes Simplify Code

  • Represent character in video game
  • Graphs
  • A customer order

Review

  • "Data classes" can make it easier to define classes with a lot of attributes
  • Typing can help make sure we don't put the wrong type of data in an attribute
  • Static variables don't change from object to object
Made with Slides.com