当前位置:网站首页>Python book learning notes - Chapter 09 section 01 create and use classes

Python book learning notes - Chapter 09 section 01 create and use classes

2022-07-06 03:56:00 Jiang Ziya will be better

9.1 Create and use classes

9.1.1 establish Dog class

   according to Dog Each instance created by the class will store the name and age , We gave each dog a squat (sit( )) And roll (roll_over( )) The ability of :

class Dog:
    """ A simple attempt to simulate a puppy """
    
    def __init__(self, name, age):
        """ Initialization property name and age."""
        self.name = name
        self.age = age
        
    def sit(self):
        """ Simulate the dog squatting down after receiving the order """
        print(f'{self.name} is now sitting.')
        
    def roll_over(self):
        """ Simulate a dog rolling when ordered ."""
        print(f"{self.name} roll over!")

   Method __init__()

   A function in a class is called a method . Everything you learned about functions earlier applies to methods , For now , The only important difference is the way the method is called . The first 4 The way to go __init__() It's a special method , Every time you look at Dog Class when a new instance is created , Python Will run it automatically .
   In the name of the method , There are two underscores at the beginning and the end , It's a convention , To avoid Python The default method has a name conflict with the normal method . Make sure that __init__() On both sides of the Two Underline , Otherwise, when you use classes to create instances , This method will not be called automatically , Which leads to hard to find errors .
   We're going to approach __init__() Defined as containing three formal parameters :self、name and age. In the definition of this method , Shape parameter self essential , And must In front of other formal parameters .
   Why must form parameters be included in the method definition self Well ? because Python Call this method to create Dog When an instance , Arguments are automatically passed in self. Each method call associated with an instance automatically passes arguments self, It is a reference to the instance itself , Gives instances access to properties and methods in the class .
   establish Dog When an instance ,Python Will call Dog Class method __init__(). We're going to go through the argument direction Dog() Pass the name and age ,self It will automatically pass , So there's no need to pass it on . Whenever according to Dog Class when an instance is created , I'm just going to give you the last two parameters (name and age) Provide value .

   attribute

   The first 4 Both variables defined at line have prefixes self. With self Variables prefixed with are available to all methods in the class , Can be accessed through any instance of the class .self.name=name Get and formal parameters name Associated value , And assign it to a variable name, This variable is then associated with the currently created instance .self.age=age The effect is similar .
   Variables that can be accessed through instances like this are called attribute .

  Dog The class also defines two other methods :sit() and roll_over(). These methods do not require additional information to execute , So they only have one parameter self.

9.1.2 Create an instance based on the class

   Create an instance that represents a particular dog :

my_dog = Dog('Willie', 6)
print(f"My dog's name is {my_dog.name}.")
print(f"My dog is {my_dog.age} years old.")

output:

My dog's name is Willie.
My dog is 6 years old.

   The first 1 That's ok , Give Way Python Create a name of 'Willie', Age is 6 The little dog .
   When I run into this line of code ,Python Using the arguments 'Willie' and 6 call Dog Class method __init__(). Method __init__() Create an instance that represents a particular dog , And use the provided value to set the property name and age.
   Next ,Python Returns an instance representing the dog , And we assign this instance to the variable my_dog. ad locum , Naming conventions are useful : Names that can usually be considered capitalized ( Such as Dog) Refers to the class , Lower case names ( Such as my_dog) Refers to an instance created from a class .

  a. Access properties —— Period notation

   The properties of the instance to access , Period notation can be used .
   Period notation Python In the common , This syntax is demonstrated Python How do I know the value of an attribute . ad locum ,Python Find the instance first my_dog, Then find the attribute associated with the instance name.
   stay Dog When this property is referenced in a class , It uses self.name and self.age.

  b. Calling method

   according to Dog Class after the instance is created , You can use the period notation to call Dog Any method defined in the class .
   Let's make the dog squat and roll :

my_dog.sit()
my_dog.roll_over()

output:

Willie is now sitting.
Willie roll over!

   To invoke a method , The name of the instance can be specified ( Here is my_dog) And the method to call , And separated by a period .
   Meet the code my_dog.sit() when ,Python In the class Dog Find method in sit() And run the code .Python Interpret the code in the same way my_dog.roll_over().
   As we can see, the output ——Willie Did as we ordered .

  c. Create multiple instances

my_dog = Dog('Willie', 6)
your_dog = Dog('Lucy', 3)
print(f"My dog's name is {my_dog.name}.")
print(f"My dog is {my_dog.age} years old.")
my_dog.sit()
print(f"\nYour dog's name is {your_dog.name}.")
print(f"Your dog is {your_dog.age} years old.")
your_dog.sit()

output:

My dog's name is Willie.
My dog is 6 years old.
Willie is now sitting.

Your dog's name is Lucy.
Your dog is 3 years old.
Lucy is now sitting.

   In this example, two puppies are created , Respectively called Willie and Lucy. Every dog is a separate instance , It has its own set of attributes , Be able to perform the same operation .
   Even if the second puppy is given the same name and age ,Python Will still be based on Dog Class creates another instance . You can create as many instances of a class as you want , The condition is that each instance is stored in a different variable , Or occupy different places in a list or dictionary .

Exercises

Create a file called Restaurant Class , For its method __init__() Set properties restaurant_name and cuisine_type.
Create a file called describe_restaurant() And a method called open_restaurant() Methods , The former prints the above two information , The latter prints a message , Point out that the restaurant is open .
Create a class named restaurant Example , Print its two properties separately , Then call the above two methods .

原网站

版权声明
本文为[Jiang Ziya will be better]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202132257200575.html