Class Things Inanimate Sidewalks Animate Animals Mammals Giraffes

  • Slides: 8
Download presentation
Class Things Inanimate Sidewalks Animate Animals Mammals Giraffes

Class Things Inanimate Sidewalks Animate Animals Mammals Giraffes

Define Class • Start from the top • Children and Parents • class Things:

Define Class • Start from the top • Children and Parents • class Things: pass class Inanimate(Things): pass class Animate(Things): pass

More about Class • class Animals(Animate) def __init__(self, age): animal_age=age def breathe(self): print(‘breathing’) def

More about Class • class Animals(Animate) def __init__(self, age): animal_age=age def breathe(self): print(‘breathing’) def move(self): print(‘moving’) self. breath() def eat_food(self): print(‘eating food’)

More about Class • class Mammals(Animals): def feed_young_with_milk(self): print(‘feeding young’) class Giraffes(Mammals): def eat_leaves_from_trees(self):

More about Class • class Mammals(Animals): def feed_young_with_milk(self): print(‘feeding young’) class Giraffes(Mammals): def eat_leaves_from_trees(self): print(‘eating leaves’)

Object • reginald=Giraffes() reginald. move() reginald. eat_leaves_from_trees() Reginald is a giraffe name Refinald, which

Object • reginald=Giraffes() reginald. move() reginald. eat_leaves_from_trees() Reginald is a giraffe name Refinald, which is the object of the class Giraffes. It’s a variable.

Initializing an Object • __init__(): a special method, which is called class constructor or

Initializing an Object • __init__(): a special method, which is called class constructor or initialization method that Python calls when you create a new instance of this class Giraffes: def __init__(self, spots) self. giraffe_spots=spots gerturde= Giraffes(150) print(gerturde. giraffe_spots)

Class Inheritance • Instead of starting from scratch, you can create a class by

Class Inheritance • Instead of starting from scratch, you can create a class by deriving it from a preexisting class by listing the parent class in parentheses after the new class name. • The child class inherits the attributes of its parent class, and you can use those attributes as if they were defined in the child class. A child class can also override data members and methods from the parent.

Functions calling other Functions • class Giraffes(Mammals) def find_food(self): self. move() print(“I’ve found food!”)

Functions calling other Functions • class Giraffes(Mammals) def find_food(self): self. move() print(“I’ve found food!”) self. eat_food()