create an instance of the Product class, uses the buy_Product() method to
decrease the inventory value, and then uses the set_price accessor method to
change the price of the product. This is starting to look like a real program!
Summary
In this hour, you learned how to create and use object-oriented programming in Python. You can
create object classes by using the class keyword, and then you define attributes and methods for the
class. You also learned how to create access and mutator methods for your classes, as well as use
many of the common helper methods to help make your coding job easier. Finally, you learned how to
save a class definition in a separate code file and then import that class as a module in other Python
scripts to use the class object.
In the next hour, we’ll dig a little deeper into the object-oriented world and look at the topic of
inheritance. That allows you to build new classes from existing classes!
Q&A
Q. Does Python support protected methods?
A. No, Python doesn’t support protected methods. You can, however, use the same idea as with
private attributes and name your method starting with two underscores. The method is still
publicly accessible, just not using the normal name.
Q. Does Python support class inheritance?
A. Yes, you can allow a class to inherit attributes and methods from another class. That’s
covered in Hour 15, “Employing Inheritance.”
Workshop
Quiz
1. Which method should you define to create default values in a class constructor?
a. __del__()
b. __init__()
c. init()
d. set_init()
2. When you instantiate two instances of a class, you can share attribute values between the two
instances. True or false?
3. How would you write an accessor method to set the value of a last name attribute?
Answers
1. b. The __init__() special method allows you to pass parameters to the class constructor that
you can use to define the default values for properties.
2. False. Separate instances of the same class are considered two separate objects, you can’t
share the same property values between them.