TUESDAY EXERCISES
Dogs: Create a Dog class that has one global attribute and two instance level attributes. the global attribute should be “species” with a value of “Canine.” the two instance attributes should be “name” and “breed.” then instantiate two dog objects, a Husky named Sammi and a Chocolate Lab named Casey.
User Input: Create a Person class that has a single instance level attribute of “name.” ask the user to input their name, and create an instance of the Person class with the name they typed in. then print out their name.
today we learned all about attributes and how we can give classes personalized variables. the use of the initialization method and self keyword allow us to declare attributes at the time of instantiation. Lastly, the difference between global and instance level attributes is key. those attributes in the initialization method cannot be accessed directly through the class but rather through instances of the class.
Wednesday: Methods
When you think about objects, you associate certain features and actions with them. Take a car, for instance. They’ll have attributes like color and wheels but also actions, such as stop, accelerate, turn, etc. In classes, these actions are known as methods. Methods are essentially functions that are within classes. If you hear someone talking about methods, you’ll instantly know that they are talking about OOP. Today, we’ll see how we can declare methods for our classes, how to call them, and why they are useful.
To follow along with this lesson, let’s continue from our notebook file “Week_07” and simply add a markdown cell at the bottom that says, “Methods.”
Defining and Calling a Method
Defining a method is the same as defining a function; however, you simply put the code within the class indentation block. When declaring a method that you intend to access through instances, you must use the self parameter in the definition. Without the self keyword, the method can only be accessed by the class itself. In order to call a method, you use dot syntax. As methods are just functions, you must call them with parenthesis after the name of the instance:
# defining and calling our first class method class Dog( ): def makeSound(self): print("bark") sam = Dog( ) sam.makeSound( )
Go ahead and run the cell. We’ll get “bark” as our output. When we created the class definition, it included the method makeSound within the blueprint. Once we created an instance of the Dog class, we were able to access the method by calling it using dot syntax. You may have as many methods as you’d like within a class.
Do'stlaringiz bilan baham: |