Class 2
Class 2
Class 2
len("Eric")
Python is checking to see whether the string object you passed it
has a length, and if it does, it returns the value associated with
that attribute. When you call
my_dict.items()
Python checks to see if my_dict has an items()method (which all
dictionaries have) and executes that method if it finds it.
Class Syntax
A basic class consists only of the class keyword, the name of the
class, and the class from which the new class inherits in
parentheses. (We’ll get to inheritance soon.) For now, our classes
will inherit from the object class, like so:
class NewClass(object):
# Class magic here
This gives them the powers and abilities of a Python object. By
convention, user-defined Python class names start with a capital
letter.
Instructions
1.
Create a class called Animal in the editor. For now, in the body of
your class, use the pass keyword. (pass doesn’t do anything, but it’s
useful as a placeholder in areas of your code where Python
expects an expression.)
INTRODUCTION TO CLASSES
Classier Classes
We’d like our classes to do more than… well, nothing, so we’ll
have to replace our pass with something else.
You may have noticed in our example back in the first exercise
that we started our class definition off with an odd-looking
function: __init__(). This function is required for classes, and it’s
used to initialize the objects it creates. __init__()always takes at
least one argument, self, that refers to the object being created.
You can think of __init__() as the function that “boots up” each
object the class creates.
Instructions
1.
Remove the pass statement in your class definition, then go ahead
and define an __init__() function for your Animal class. Pass it the
argument selffor now; we’ll explain how this works in greater
detail in the next section. Finally, put the pass into the body of
the __init__() definition, since it will expect an indented block.
Hint
Your __init__() function should look something like this:
def __init__(self):
pass
Question
What is the difference between a class and an object?
Answer
Think of a class as a blueprint and an object as the result of creating
what that blueprint specified.
Classes allow us to define a general state and behavior for the
objects we want to make. This is a super powerful way to approach
programming because it allows for us to generalize our code to work
for many situations!
For example, we might make a Car class that has things you might
find in any car: wheel_count, gas_tank_size, and a seat_count of at
least one for the driver to sit in. When we create an object of
type Car, we might make a mustang object (notice it’s lowercase, as
is convention when instantiating objects of a class). Our mustang has
its own values for those variables because it’s different from
other Cars, but still has a lot of the same properties. We could make an
object for any model of car!
Same basic structure, different values. That’s the use of a class!
INTRODUCTION TO CLASSES
Instructions
1.
Let’s do two things in the editor:
Hint
Your syntax should look like this:
class Animal(object):
def __init__(self, name):
# Set the name parameter here!
Question
What is self?
Answer
self’s purpose may not seem very obvious at first, especially if you’ve
never used an object-oriented programming language before!
Try to imagine a class named Car that has the basic structure that
all cars share in common. It defines a basic acceleration behavior, but
not how fast it accelerates or what the max speed is, as that varies
from car to car. It defines a start method, but not the specifics of
how it starts, as that varies as well.
Now imagine that we’ve created Car objects of all the models we can
think of. So now we have a mustang object, a tesla_model_x object,
etc. Upon creation we can now specify how a particular model
accelerates or starts. Inside of our Car’s __init()__ method we
use self to refer to the current car model so we can assign values
like top speeds and whatnot.
The current car model is one attribute of the car
instance. self refers to the instance in context scope, that is
the current instance, i.e., the instance upon which the call is made.
my_car.model
my_car.color
my_car.mpg
INTRODUCTION TO CLASSES
class Square(object):
def __init__(self):
self.sides = 4
my_shape = Square()
print my_shape.sides
Instructions
1.
Outside the Animal class definition, create a variable
named zebra and set it equal to Animal("Jeffrey").
Then print out zebra‘s name.
Hint
You can create a new Animal object named "Jeffrey" like this:
zebra = Animal("Jeffrey")
You can print out "Jeffrey"‘s name like this:
print zebra.name
INTRODUCTION TO CLASSES
Answer
Python knows that the __init__() method’s first parameter, typically
called self, is assigned to the object you create when you initialize it.
That way you can use self throughout your class to accomplish
things with that particular object!
If you do pass something for self when initializing an object, you’ll
get an error about the number of arguments provided and the number
of arguments expected. This is because whatever you pass starts by
giving value to the second, third, fourth, and so on, parameters.
In our Animal example, we have 4 parameters total: self, name, age,
is_hungry. However, if we try to pass it 4 arguments when we call it,
we’re actually passing it 5, because it automatically passes self!
INTRODUCTION TO CLASSES
Class Scope
Another important aspect of Python classes is scope. The scope of
a variable is the context in which it’s visible to the program.
It may surprise you to learn that not all variables are accessible to
all parts of a Python program at all times. When dealing with
classes, you can have variables that are available everywhere
(global variables), variables that are only available to members of
a certain class (member variables), and variables that are only
available to particular instances of a class (instance variables).
A Methodical Approach
When a class has its own functions, those functions are
called methods. You’ve already seen one such method: __init__().
But you can also define your own methods!
Instructions
1.
Add a method, description, to your Animal class. Using two
separate printstatements, it should print out the nameand age of the
animal it’s called on. Then, create an instance of Animal, hippo (with
whatever name and age you like), and call its description method.
Hint
Remember to pass self as an argument to description. Otherwise,
printing self.nameand self.age won’t work, since Python won’t know
which self (that is, which object) you’re talking about!
def description(self):
print self.name
print self.age
After that, all you need to do is create a hippoand call its
description method with hippo.description()!
Question
How can I create a new Animal object and use its description method?
Answer
Remember, creating a new object of a class looks like this:
object_name = ClassName("arguments_here")
Then, to use the description() method of our new Animal, we simply
call that method attached to our new object, like this:
object_name.method_name()
INTRODUCTION TO CLASSES
They're Multiplying!
A class can have any number of member variables. These are
variables that are available to all members of a class.
is_alive = True
health = "good"
You can print out your hippo‘s health with
print hippo.health
INTRODUCTION TO CLASSES
my_cart = ShoppingCart("Eric")
Calling the add_item() method might then be:
my_cart.add_item("Ukelele", 10)
INTRODUCTION TO CLASSES
Answer
We’ve learned so far about a few of the concepts that are core in
almost any object-oriented language. The big three features typically
associated with object orientation are polymorphism, encapsulation,
and inheritance.
For the purposes of this course, it’s plenty to understand that objects
can inherit from each other, can define how their data is accessed, and
how to create and use classes and objects.
If you’re up for a challenge, a quick Google search for those other
object-oriented properties will provide a rabbit hole to keep you busy
for days! To start you off, this StackOverflow post’s top
answer 605 gives some great insights about what defines object
orientation.
29
Definitions for Object-Orientation are of course a huge can of worms, but here
are my 2 cents:
To me, Object-Orientation is all about objects that collaborate by sending
messages. That is, to me, the single most important trait of an object-
oriented language.
Inheritance Syntax
In Python, inheritance works like this:
class DerivedClass(BaseClass):
# code goes here
where DerivedClass is the new class you’re making and BaseClass is the
class from which that new class inherits.
Instructions
1.
On lines 1-4, we’ve created a class named Shape.
class Triangle(Shape):
def __init__(self, side1, side2, side3):
self.side1 = side1
self.side2 = side2
self.side3 = side3
Question
How will Triangle objects know which init method to use?
Answer
In this exercise we’ve defined a new class called Triangle that
inherits from the base class Shape. Both classes define
an __init__() method! Luckily, Python is smart enough to see that we
intended to use the initialize method in our Triangle class when
creating a new Triangle object.
Python checks the object that called the method and sees that it has a
method of the same name that then takes priority over the one in the
base class.
In the case of __init__() being defined twice, it sees that we’re
initializing a Triangle, so we use that method.
INTRODUCTION TO CLASSES
Override!
Sometimes you’ll want one class that inherits from another to not
only take on the methods and attributes of its parent, but
to override one or more of them.
class Employee(object):
def __init__(self, name):
self.name = name
def greet(self, other):
print "Hello, %s" % other.name
class CEO(Employee):
def greet(self, other):
print "Get back to work, %s!" % other.name
ceo = CEO("Emily")
emp = Employee("Steve")
emp.greet(ceo)
# Hello, Emily
ceo.greet(emp)
# Get back to work, Steve!
Rather than have a separate greet_underlingmethod for our CEO, we
override (or re-create) the greet method on top of the
base Employee.greet method. This way, we don’t need to know what
type of Employee we have before we greet another Employee.
Instructions
1.
Create a new class, PartTimeEmployee, that inherits from Employee.
Because PartTimeEmployee.calculate_wageoverrides Employee.calculate_wage, it
still needs to set self.hours = hours.
Answer
The point of overriding is to allow different behavior from the same
function in different classes.
In our Employee and PartTimeEmployee example, we want both
employees to be paid, so we create a method to calculate their wages.
And since a part time employee is definitely a type of Employee, it
makes sense for them to derive a lot of the same functionality.
However! That doesn’t mean their pay should be calculated in the
same way. So we override the calculate_wage method to behave as
we want it to for PartTimeEmployee objects.
By defining a method with the same name as found in the base
class, Employee, we are overriding the functionality so that
any PartTimeEmployees will have their wages calculated appropriately.
INTRODUCTION TO CLASSES
class Derived(Base):
def m(self):
return super(Derived, self).m()
Where m() is a method from the base class.
Instructions
1.
First, inside your PartTimeEmployee class:
Hint
You super call should look something like this:
Class Basics
First things first: let’s create a class to work with.
Instructions
1.
Create a class, Triangle. Its __init__()method should
take self, angle1, angle2, and angle3 as arguments. Make sure to set
these appropriately in the body of the __init__() method (see the
Hint for more).
Hint
Make sure your Triangle inherits from object. Remember, class
syntax looks like this:
class ClassName(object):
def __init__(args):
# Set self.args = args
INTRODUCTION TO CLASSES
Class It Up
Great! Now let’s add a member variable and a method to our
class.
Instructions
1.
Inside the Triangle class:
Hint
The check_angles method should look something like this:
def check_angles(self):
if (self.angle1 + self.angle2 + self.angle3 == 180):
return True
else:
return False
INTRODUCTION TO CLASSES
Instantiate an Object
Let’s go ahead and create an instance of our Triangle class.
Instructions
1.
Create a variable named my_triangleand set it equal to a new
instance of your Triangle class. Pass it three angles that sum to 180
(e.g. 90, 30, 60).
Print out my_triangle.number_of_sides
Print out my_triangle.check_angles()
Hint
Remember, we can instantiate an object like so:
instance = Class(args)
Where args are the arguments __init__()takes, not including self.
INTRODUCTION TO CLASSES
Inheritance
Finally, let’s create an Equilateral class that inherits from
our Triangle class. (An equilateral triangle is a triangle whose
angles are all 60˚, which also means that its three sides are equal
in length.)
Instructions
1.
Create a class named Equilateral that inherits from Triangle.
class DerivedClass(BaseClass):
# Your code here
where DerivedClass is the new class you’re making, and BaseClass is
the class it inherits from.
CLASSES
Class basics
Classes can be very useful for storing complicated objects with
their own methods and variables. Defining a class is much like
defining a function, but we use the class keyword instead. We also
use the word object in parentheses because we want our classes
to inherit the object class. This means that our class has all the
properties of an object, which is the simplest, most basic class.
Later we’ll see that classes can inherit other, more complicated
classes. An empty class would look like this:
class ClassName(object):
# class statements go here
Instructions
1.
Define a new class named “Car”. For now, since we have to put
something inside the class, use the pass keyword.
Question
What are the properties of ‘object’, the simplest and most basic class?
Answer
In Python, the object from which all classes inherit their most basic
properties is called object. This allows us to customize everything
about our new class, including how to initialize it, how to set
descriptors, accepting arguments, and more.
For an in-depth view, take a look at the top answer of this
StackOverflow post 643 about the object we inherit from!
CLASSES
newObject = ClassName()
Instructions
1.
Below your Car class, create a new object named my_car that is an
instance of Car.
CLASSES
class ClassName(object):
memberVariable = "initialValue"
Instructions
1.
Inside your Car class, replace the passstatement with a new
member variable named condition and give it an initial value of the
string "new".
Question
What makes member variables useful?
Answer
Member variables are those that you want to be the same across all
objects of a class. In our Carexample, all cars should start off
in new condition, so we set condition = "new" as a member variable.
However, things that might differ from car to car are
their name and year_model! So for those things that are not the same
across the board, we create instance variables.
CLASSES
Answer
If you’re trying to access a member variable, you do not need
parentheses at the end, otherwise it looks for a method with the name
you typed.
To access a member variable, we simply type the name of the variable
after a dot connected to the object we want to access, like this:
print my_object.property_name
CLASSES
Initializing a class
There is a special function named __init__()that gets called
whenever we create a new instance of a class. It exists by default,
even though we don’t see it. However, we can define our
own __init__() function inside the class, overwriting the default
version. We might want to do this in order to provide more input
variables, just like we would with any other function.
self.new_variable = new_variable
Instructions
1.
Define the __init__() function of the Car class to take four inputs:
self, model, color, and mpg. Assign the last three inputs to
member variables of the same name by using the self keyword.
model = "DeLorean"
color = "silver"
mpg = 88
You don’t need to include the selfkeyword when you create an
instance of a class, because self gets added to the beginning of
your list of inputs automatically by the class definition.
Hint
Creating an instance of a class with many initialization variables
looks the same as calling a function with many inputs; put all the
values in parentheses, separated by commas.
Question
How does init know what values to assign to instance variables?
Answer
If we make an __init__() method that accepts the same parameters
as our Car class, like this: (self, model, color, mpg), then these are
the values that will be provided whenever you create a
new Car object.
When a new Car object is created, the values provided as arguments
for those parameters are then given to you for use inside
the __init__() method. That’s where we’re able to create new
instance variables with the structure: self.variable_name =
variable_name. The left side uses self to tell Python to create a new
instance variable for this particular object we just made, and then the
right side is the value we store in that new variable, which is just the
argument value.
CLASSES
new_object.new_variable
Instructions
1.
Now that you’ve created my_car print its member variables:
Hint
To print my_car‘s model, you’d type:
print my_car.model
CLASSES
class Square(object):
def __init__(self, side):
self.side = side
def perimeter(self):
return self.side * 4
The perimeter() class method is identical to defining any other
function, except that it is written inside of the Square class
definition.
Answer
The steps must be followed in exactly the order asked for in the
instructions, otherwise you’ll get errors saying that you didn’t print or
change something properly.
In this order, we should:
Inheritance
One of the benefits of classes is that we can create more
complicated classes that inherit variables or methods from
their parent classes. This saves us time and helps us build more
complicated objects, since these child classes can also include
additional variables or methods.
class ChildClass(ParentClass):
# new variables and functions go here
Normally we use object as the parent class because it is the most
basic type of class, but by specifying a different class, we can
inherit more complicated functionality.
Instructions
1.
Create a class ElectricCar that inherits from Car. Give your new class
an __init__() method of that includes a battery_type member variable
in addition to the model, color and mpg.
Overriding methods
Since our ElectricCar is a more specialized type of Car, we can
give the ElectricCar its own drive_car() method that has different
functionality than the original Car class’s.
Instructions
1.
Inside ElectricCar add a new method drive_car that changes the
car’s condition to the string "like new".
Finally, print my_point.
Hint
When defining a new __repr__(), return a string value that uses the
member variables of the class to display the 3D point properly.
You can use the str() function to put these numbers in the proper
string.
Answer
In our class Print3D, there are a few key points to make
our __repr__() method useful.
Be sure to pass self to any class method, including __repr__(), like
this: def __repr__(self):
Inside we need to define how our object is printed. Whenever the built-
in print function receives our object, it looks for
a __repr__() method, and if it’s found, it prints the return value to
the screen! So we just return what the instructions ask: "(%d, %d,
%d)" % (self.x, self.y, self.z)