MONDAY EXERCISES
1. Animals: Create a class called “animals,” and create two instances from it. Use two variables with names of “lion” and “tiger.”
2 . Problem-Solving: What’s wrong with the following code?
>>> class Bus:
>>> pass
>>> school_bus = Bus( )
today was the first step into the world of object-oriented programming. in order to build objects in python, we must first create class definitions, also known as blueprints. From there, we can create single or multiple instances from that class.
this process is known as instantiation. tomorrow we’ll see how we can give features to each instance.
Tuesday: Attributes
Yesterday we saw how to create a class definition. Today, we’ll begin to understand how to give personalized features, known as attributes, to classes and their instances. Attributes are just variables defined within a class, nothing more than that. If you hear someone talking about attributes, you’ll immediately know that they’re speaking about classes. An attribute is how we store personal information for each object instance. Think of an attribute as a source of information for an object. For a car, an attribute could be the color, number of wheels, number of seats, the engine size, etc.
To follow along with this lesson, let’s continue from our previous notebook file
“Week_07” and simply add a markdown cell at the bottom that says, “Attributes.”
Declaring and Accessing Attributes
Like variables, we declare attributes with a name and value; however, they are declared inside of the class. We’ve talked about scope in a previous week; attributes are only available within classes they are defined, so in order to access an attribute, you must create an instance:
# how to define a class attribute class Car( ):
sound = "beep" # all car objects will have this sound attribute and its' value
color = "red" # all car objects will have this color attribute and its' value
ford = Car( ) print(ford.color) # known as 'dot syntax'
Go ahead and run the cell. The output will result in “red”. When we instantiated the ford variable from the Car class, it was created with two attributes. These attributes were automatically set within the class definition, so every instance created from the Car class will be given the sound “beep” and the color “red.” We’ll see how we can change this later. In order to access an object’s attribute, you use dot syntax. You start by writing the name of the instance, followed by a dot and the attribute you want to access. All classes use this similar dot syntax in order to access attributes and methods (more on methods tomorrow).
Do'stlaringiz bilan baham: |