Getting Started with Python (19) Class (2)

1. Working with classes and instances

Classes can be used to simulate many situations in the real world. Once the class is written, most of our time will be spent creating instances from the class. One important task we need to perform is to modify the properties of the instance. You can modify the properties of the instance directly, or you can write methods to modify them in a specific way.

1.1 car class

Let's write a class that represents a car. It stores information about cars, and has a method to aggregate this information:

  class Car:
      """一次模拟汽车的简单尝试。"""

      def __init__(self, make, model, year):
          """初始化描述汽车的属性。"""
          self.make = make
          self.model = model
          self.year = year

      def get_descriptive_name(self):
          """返回整洁的描述性信息。"""
          long_name = f"{
      
      self.year} {
      
      self.make} {
      
      self.model}"
          return long_name.title()
  my_new_car = Car('audi', 'a4', 2019)
  print(my_new_car.get_descriptive_name())

The method __init__() is defined. As in the previous Dog class, the first parameter of this method is self. The method also contains three other parameters: make, model, and year. The method __init__() takes the values ​​of these parameters and assigns them to attributes of instances created from this class. When creating a new Car instance, you need to specify its manufacturer, model, and production year.

A method named get_descriptive_name() is defined. It uses the attributes year, make, and model to create a string that describes the car, saving us from printing the value of each attribute separately. To access the value of the property in this method, self.make, self.model and self.year are used.

An instance of the Car class is created and assigned to the variable my_new_car. Next, call the method get_descriptive_name() to indicate what kind of car we own:

2019 Audi A4

To make this class more interesting, let's add a time-varying property to store the total mileage of the car.

1.2 Assign default values ​​to attributes

When creating an instance, some attributes do not need to be defined through formal parameters, and default values ​​can be specified for them in the method __init__().

Let's add a property called odometer_reading whose initial value is always 0. We also added a method called read_odometer() to read the car's odometer:

  class Car:

      def __init__(self, make, model, year):
          """初始化描述汽车的属性。"""
          self.make = make
          self.model = model
          self.year = year
          self.odometer_reading = 0

      def get_descriptive_name(self):
          --snip--
      def read_odometer(self):
          """打印一条指出汽车里程的消息。"""
          print(f"This car has {
      
      self.odometer_reading} miles on it.")

  my_new_car = Car('audi', 'a4', 2019)
  print(my_new_car.get_descriptive_name())
  my_new_car.read_odometer()

Now, when Python calls the method __init__() to create a new instance, the manufacturer, model, and year of production are stored as attributes as in the previous example. Next, Python will create an attribute called odometer_reading and set its initial value to 0. Define a method called read_odometer() that allows you to easily get the mileage of the car1.

At the beginning the mileage of the car is 0:

2019 Audi A4
This car has 0 miles on it.

Not many cars are sold with an odometer reading of 0, so we need a way to modify the value of this property.

1.3 Modify the value of an attribute

We can modify the value of a property in three ways: directly through the instance, set through a method, and incremented (increase a specific value) through a method. These methods are described in turn below.

Modify the value of the property directly

To modify the value of a property, the easiest way is to access it directly through the instance. The following code directly sets the odometer reading to 23:

  class Car:
      --snip--

  my_new_car = Car('audi', 'a4', 2019)
  print(my_new_car.get_descriptive_name())

  my_new_car.odometer_reading = 23
  my_new_car.read_odometer()

Use period notation to directly access and set the car's property odometer_reading. This line of code tells Python to find the attribute odometer_reading in the instance my_new_car and set its value to 23:

2019 Audi A4
This car has 23 miles on it.

Sometimes you need to access properties directly like this, but other times you need to write methods that update properties.

Modify the value of the attribute through the method

It would be helpful if there was a way to update properties for you. This eliminates the need to access the property directly, and instead passes the value to the method, which updates it internally.

The following example demonstrates a method named update_odometer():

  class Car:
      --snip--

      def update_odometer(self, mileage):
          """将里程表读数设置为指定的值。"""
          self.odometer_reading = mileage

  my_new_car = Car('audi', 'a4', 2019)
  print(my_new_car.get_descriptive_name())

  my_new_car.update_odometer(23)
  my_new_car.read_odometer()

The only modification made to the Car class is the addition of the method update_odometer(). This method takes an odometer value and assigns it to self.odometer_reading. update_odometer() is called, and it is given the argument 23 (which corresponds to the formal parameter mileage in the method definition). It sets the odometer reading to 23, and the method read_odometer() prints that reading:

2019 Audi A4
This car has 23 miles on it.

The method update_odometer() can be extended to do some extra work when modifying the odometer reading. Let's add some logic to prevent anyone from calling back the odometer reading:

  class Car:
      --snip--

      def update_odometer(self, mileage):
          """
          将里程表读数设置为指定的值。
          禁止将里程表读数往回调。
          """
          if mileage >= self.odometer_reading:
              self.odometer_reading = mileage
          else:
              print("You can't roll back an odometer!")

update_odometer() now checks that the specified reading is reasonable before modifying properties. If the newly specified mileage (mileage) is greater than or equal to the original mileage (self.odometer_reading), change the odometer reading to the newly specified mileage; otherwise, issue a warning that the odometer cannot be called back.

Incrementing the value of a property via a method

Sometimes it is desirable to increment a property value by a specific amount, rather than setting it to an entirely new value. Let's say we buy a used car and add 100 miles on it between purchase and registration. The following method allows us to pass this increment and increment the odometer reading accordingly:

  class Car:
      --snip--

      def update_odometer(self, mileage):
          --snip--

      def increment_odometer(self, miles):
          """将里程表读数增加指定的量。"""
          self.odometer_reading += miles

  my_used_car = Car('subaru', 'outback', 2015)
  print(my_used_car.get_descriptive_name())

  my_used_car.update_odometer(23_500)
  my_used_car.read_odometer()

  my_used_car.increment_odometer(100)
  my_used_car.read_odometer()

The new method increment_odometer() accepts a number in miles and adds it to self.odometer_reading.

Create a used car my_used_car.

Call the method update_odometer() and pass in 23_500 to set the odometer reading of this used car to 23 500.

Call increment_odometer() and pass in 100 to add 100 miles traveled between purchase and check-in.

2015 Subaru Outback
This car has 23500 miles on it.
This car has 23600 miles on it.

We can easily modify this method to disallow negative increments, preventing someone from using it to call back the odometer.

Note that you could use a method similar to the above to control how users can modify property values ​​such as the odometer reading, but anyone with access to the program can change the odometer to any value by directly accessing the property. To be safe, in addition to basic inspections similar to the previous ones, special attention to detail is required.

Guess you like

Origin blog.csdn.net/qq_41600018/article/details/131155723