Class 24 - Objects and Classes
Schedule
Project 5: Tic-Tac-Go! is now posted. To be well on track to complete the Red Belt (criterion for earning an A in the course), you should complete it by Monday, 11 April.
Slides
Notes
What is an object?
What is a class?
Defining a Class
class Dog:
def __init__(self):
self.hungry = True
def eat(self):
self.hungry = False
def bark(self):
if self.hungry:
print("ham ham ham ham!")
else:
print("yap yap yap")
Exploring Objects
Python provides some useful built-in functions for exploring objects.
type(object) returns the type of object:
>>> type(3)>>> type("hello") >>> type([1, 2, 3]) >>> scooby = Dog() >>> type(scooby)
isinstance(object, type) returns True if object is an instance of type type, False otherwise:
assert isinstance(scooby, object) assert isinstance(3, int) assert not isinstance(3, str) assert isinstance(scooby, Dog) assert isinstance(scooby, object) assert isinstance(3, object)
dir(object) returns a list of all the valid attributes for object (i.e., object.attribute):
>>> dir(3) ['__abs__', '__add__', ..., '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes'] >>> dir(scooby) ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', ..., '__str__', '__subclasshook__', '__weakref__', 'bark', 'eat', 'hungry']
Note that we only defined the __init__, bark, eat, and hungry
methods for Dog. All the other methods were inherited from its
(default) superclass, object.