"Python programming from introduction to practice" -- creating and using classes

Posted by Big_Ad on Sun, 19 Dec 2021 09:36:50 +0100

Create class

  introduction to object-oriented technology

  1. Class: used to describe a collection of objects with the same properties and methods. It defines the properties and methods common to each object in the collection. An object is an instance of a class.
  2. Method: a function defined in a class.
  3. Class variables: class variables are common to the entire instantiated object. Class variables are defined in the class and outside the function body. Class variables are usually not used as instance variables.
  4. Data members: class variables or instance variables are used to process data related to classes and their instance objects.
  5. Method override: if the method inherited from the parent class cannot meet the needs of the child class, it can be overridden. This process is called method override, also known as method override.
  6. Local variable: the variable defined in the method, which only acts on the class of the current instance.
  7. Instance variable: in the declaration of a class, attributes are represented by variables, which are called instance variables. Instance variables are variables decorated with self.
  8. Inheritance: that is, a derived class inherits the fields and methods of the base class. Inheritance also allows the object of a derived class to be treated as a base class object.
  9. Instantiation: create an instance of a class and a concrete object of the class.
  10. Object: an instance of a data structure defined by a class. The object consists of two data members (class variables and instance variables) and methods.

  compared with other programming languages, python adds a class mechanism without adding new syntax and semantics as much as possible. Classes in Python provide all the basic functions of object-oriented programming: the inheritance mechanism of classes allows multiple base classes, derived classes can override any method in the base class, and methods with the same name in the base class can be called. Objects can contain any number and type of data.


  by convention, in Python, capitalized names refer to classes. The parentheses in the class definition are empty because we want to create the class from blank. The functions in the class are called methods; Everything you've learned about functions applies to methods. For now, the only important difference is the way you call methods. The method init() is a special method. Whenever you create a new instance based on the person class, python will run it automatically. In the name of this method, there are two underscores at the beginning and end, which is a convention to avoid name conflicts between Python default methods and ordinary methods.


  in the definition of init() method, the formal parameter self is essential and must precede other formal parameters. Why must the formal parameter self be included in the method definition? Because Python calls this__ init__ () method to create first_ When the person instance is, the argument self is automatically passed in. Each method call associated with the class automatically passes the argument self, which is a reference to the instance itself, so that the instance can access the properties and methods in the class. We create first_ When the person instance is, python calls the method of the person class__ init__ (). We will pass the name, age and gender to person through the arguments; Self is passed automatically, so we don't need to pass it. Whenever we create an instance based on the person class, we only need to provide values for the last three formal parameters (name, age, and sex).


  all variables defined have the prefix self. Variables prefixed with self can be used by all methods in the class, and we can access them through any instance of the class. self.name = name gets the value stored in the formal parameter name and stores it in the variable name, and then the variable is associated with the currently created instance. Variables that can be accessed through instances like this are called properties.




  the following is a created example.

# input
class person(object): # Creat person class including name, age, sex
    def __init__(self,name,age,sex):   # input related info 
        self.name = name
        self.age = age
        self.sex = sex
    def get_age(self):              # get person age
        print(self.name.title() + "'s age is " + " " + str(self.age))
    def get_sex(self):              # get person sex
        print(self.name.title() + "'s sex is " + " " + self.sex)

    
first_person = person('tom','80','male')
second_persion = person('jerry','82','femal')
first_person.get_age()
second_person.get_sex()


# output
Tom's age is  80
Jerry's sex is  femal

  1. Access properties
  to access the properties of an instance, use the period notation. Period notation is commonly used in Python. This syntax demonstrates how Python knows the value of an attribute. Here, python first finds the instance first_person, and then find the attribute name associated with this instance. When you reference this attribute in the person class, you use self name.
  2. Call method
  after creating an instance from the person class, you can use the period notation to call any method defined in the person class. To call a method, specify the name of the instance (here first_person) and the method to call, and separate them with a period. When encountering the code first_person.get_age(), Python looks for the method get in the class person_ Age () and run its code. This grammar is very useful. If you specify appropriate descriptive names for properties and methods, such as name, age, sit(), and roll_over(), even if it's a code block we've never seen before, we can easily infer what it does.
  3. Create multiple instances
  any number of instances can be created according to the class as required. Even if we give the second person the same name and age, Python will still create another instance based on the person class. You can create any number of instances according to a class as needed, provided that each instance is stored in a different variable or occupies a different location in a list or dictionary.



















Use class

  you can use classes to simulate many situations in the real world. After the class is written, you will spend most of your time using the instances created from the class. An important task you need to perform is to modify the properties of the instance. You can modify the instance properties directly, or write methods to modify them in a specific way. Every property in a class must have an initial value, even if the value is 0 or an empty string. In some cases, such as when setting the default value, in the method__ init__ It is feasible to specify such initial value in (); If you do this for a property, you do not need to include a formal parameter that provides an initial value for it.

# input
class Car(object):
    def __init__(self,band,model,year):
        self.band = band
        self.model = model
        self.year = year
        self.mile = 300

    def get_info(self):
        print(
            "My car is " + self.band.title() + " "
            + self.model + " and bought in " + str(self.year))

    def report_odometer(self):
        print("The mile drving is " + str(self.mile))

my_car = Car("BWM",'I8',2020)
my_car.report_odometer()

# output
The mile drving is 300

  in the actual process, our vehicle mileage changes from time to time, so we modify the attribute value in the process of executing the program. Here is how to modify the attribute value.
  1. Directly modify the value of the attribute
  the easiest way to modify the value of a property is to access it directly through an instance. Sometimes you need to access properties directly like this, but other times you need to write methods to update properties.

# input
class Car(object):
    def __init__(self,band,model,year):
        self.band = band
        self.model = model
        self.year = year
        self.odometer = 0

    def getinfo(self):
        print("my car is " + self.band + " " + self.model + " and is bought in " + str(self.year))

    def reportinfo(self):
        print("The odometer is " + str(self.odometer))


my_car = Car("BWM","I8",2021)
my_car.getinfo()
my_car.odometer = 300
my_car.reportinfo()

# output
my car is BWM I8 and is bought in 2021
The odometer is 300

  2. Modify the value of an attribute through the method
  it would be helpful if there were a way to update properties for you. In this way, you don't need to access the property directly, but you can pass the value to a method, which updates it internally. The only modification made to the Car class is the addition of the method update at _ odometer(). This method takes a mileage value and stores it in self odometer_ Reading. We called update_odometer() and provides it with arguments.

# input
class Car(object):
    def __init__(self,band,model,year):
        self.band = band
        self.model = model
        self.year = year

    def getinfo(self):
        print("my car is " + self.band + " " + self.model + "and is bought in " + str(self.year))

    def reportmileinfo(self,odometer):
        self.odometer = odometer
        print("The odometer is " + str(self.odometer))


my_car = Car("BWM","I8",2021)
my_car.reportmileinfo(230)

# output
The odometer is 230

  3. Increment the value of the attribute by method
  sometimes you need to increment the attribute value by a specific amount instead of setting it to a new value. Suppose we buy a used car and add 100 miles from purchase to registration, the following method allows us to pass this increment and increase the odometer reading accordingly. You can use a method similar to the above to control how users modify attribute values (such as odometer readings), but anyone who can access the program can modify the odometer to any value by directly accessing the attribute. To ensure security, in addition to the basic checks similar to the previous ones, special attention should be paid to details.

# input
class Car(object):
    def __init__(self,band,model,year):
        self.band = band
        self.model = model
        self.year = year
        self.odometer = 100

    def getinfo(self):
        print("my car is " + self.band + " " + self.model + "and is bought in " + str(self.year))

    def reportmileinfo(self,odometer):
        self.odometer += odometer
        print("The odometer is " + str(self.odometer))


my_car = Car("BWM","I8",2021)
my_car.reportmileinfo(230)

# output
The odometer is 330

  private sex
  1. Private properties of class
  __ private_attrs: it starts with two underscores and declares that the attribute is private and cannot be used or accessed directly outside the class. When used in methods inside a class, self__ private_attrs.

# input
class Car(object):
    __username = "Youth"

    def __init__(self,band):
        self.band = band

    def printband(self):
        print(self.band)

mycar = Car("Adui")
print(mycar.band)
print(mycar.__username)


# output
Adui
Traceback (most recent call last):
  File "C:/script/Class2.py", line 12, in <module>
    print(mycar.__username)
AttributeError: 'Car' object has no attribute '__username'

  2. Private method of class
  __ private_method: it starts with two underscores and declares that the method is private. It can only be called inside the class, not outside the class. self.__private_methods.

# input
class Car(object):
    def __init__(self,band):
        self.band = band
        

    def printband(self):
        print(self.band)

    def __printage(self):
        print(str(24))

mycar = Car("Adui")
mycar.printband()
mycar.__printage()

# output
Adui
Traceback (most recent call last):
  File "C:/script/Class2.py", line 14, in <module>
    mycar.__printage()
AttributeError: 'Car' object has no attribute '__printage'
Class
NameDescription
__init__ Constructor, called when the object is generated
__del__Destructor, used when releasing an object
__repr__ Printing, converting
__setitem__ Assignment by index
__getitem__Get value by index
__len__Get length
__cmp__Comparison operation
__call__function call
__add__Addition operation
__sub__Subtraction operation
__mul__Multiplication operation
__truediv__Division operation
__mod__Remainder operation
__pow__Power

Topics: Python