Python basic syntax - object oriented: classes and objects

Syntax:

class Class name:
    Attribute value
    Class function
#Create instance
 Class name ()

Specification: 1) the first letter of each word of class name shall be capitalized, and the identifier big hump naming method shall be followed  .

            2) When naming a class name, you should see the meaning of the name to improve the readability of the code.

1. How to define a class?

All you think have common attributes and common characteristics can be divided into one category. For example, you and I, we are single, have no boyfriend or girlfriend, then we can be divided into single category; For example, there is a person who has characteristics that no one else has. He has thousands of miles' eyes. Can he be classified as one? Yes, a person is also a class, because a class is a collection with the same characteristics and behavior, and the collection can have only one value or be empty.

2. What is the object?

An object is a member (individual) of a class of things. An object, also known as an instance, is an entity and member of a class. For example, a specific person (you or me) in the single class is an object (instance).

class Dog:
    pass


# Get a class
print(Dog)
# Get an object / instance
print(Dog())

Running result: 0x000001C5D39A44A8 indicates the memory address of the object

3. Relationship between class and object

Class is equivalent to the construction drawing (template) when building a car, and the built car is the object.

class Car:
    pass


# Get a class
print(Car)
# Get an object / instance
my_car = Car()
print(my_car)
# Create another object / instance
your_car = Car()
print(your_car)
# Two different objects, not equal
print(my_car == your_car)
print(Car() == Car())

Operation results:

  4. Class attribute

Class attribute: in a class, all members have the same characteristics.

Instance attribute: the characteristics of a member of a class, individual characteristics.

python represents class attributes and instance attributes (outside the class). Take the following code as an example:

Class attribute: class name. Class attribute, car.driven
 Instance attribute: class name (). Class attribute, car (). Driven

Modify attribute value:

1) After modifying a class property through a class, get the properties and instance properties of the class. All of them will change and get a new value

Car.elements = ['leather']
#Get class properties
 Print (car. Elements) = > ['leather']
#Get an object that can get the variables of the class
my_car = Car()
Print (my_car. Elements) = > ['leather']

2) After modifying an attribute through an object, the class attribute remains unchanged and the instance attribute takes a new value

my_car.drived= False
 #Gets the driven of the object
print(my_car.drived) ==>False
 #Gets the driven property of the class
print(Car.drived)  ==>True

Example: define a Car class with the same class attribute: wheel  , drived ,elements  

# In the scope of class definition, defining variables is class attributes
class Car:
    # Class attribute / class variable
    wheel = True
    drived = True
    elements = ['Plastic', 'iron', 'rubber']
    # Class to get class variables
    print(f'wheel:{wheel}')


# How to get class variables? Get class variables outside the class
print(Car.elements)
# This is not possible because elements are local variables
# print(elements)#Writing of global variables

# Modify class properties
Car.wheel = False
print(Car.wheel)
Car.elements = ['genuine leather']
print(Car.elements)

# Get an object that can get the variables of the class
my_car = Car()
print(my_car.elements)

# The difference between modifying class properties and modifying instance properties
my_car.drived= False
# Gets the driven of the object
print(my_car.drived)
# Gets the driven property of the class
print(Car.drived)

Operation results:

  

  5.__init__ And instance variables

  • __ init__ Called initialization method, it represents the initialization process generated by an object.
  • In essence, a method is a function, and you can add parameters, that is, instance attributes
  • __ init__ no return value

If in a class, do not write__ init__ Function, but there is also a default, as shown in the following code:

class Car:
    element = ['iron']

    def __init__(self):
        pass


# Get a class
print(Car)
# The process of creating an object through the template of class is the instantiation process
# The specific process in Car() is actually in the automatic calling class__ init__ This function (initialization function),
#You do not need to specify a function name
print(Car())

This kind of function has parameters: for example, to produce a car, you need to put the chassis, install the frame, install the tires, spray paint and print the logo.

class Car:
    element = ['iron']

    def __init__(self,color,logo):  # You must add self
        print('One Car Object is being generated')
        print('Perform the first step first: lower the chassis')
        print('Then perform the second step: install the frame')
        print('Then perform the third step: install the tire')
        print(f'Then proceed to step 4: paint color:{color}')
        print(f'Then perform step 5: printing{logo}logo')


# Get a class
print(Car)
# The process of creating an object through the template of class is the instantiation process
# The specific process, in the object of obtaining Car(), is actually in the automatic calling class__ init__ This function (initialization function) does not need to specify the function name
# What's the use of functions? You can specify the process of generating objects yourself
print(Car(color='red',logo='Porsche'))
print(Car('green','The Beatles'))

Operation results:

 self

It means that during the production process of the object, a mark representing the object, such as a newborn will have a bracelet lock, which is used to mark whose child is and prevent wrong holding or theft. The instrument alarm will be triggered when passing through the door of the hospital without being unlocked by the doctor.

Self is used in the class definition. There is no self outside the class. For example, this bracelet lock is used in the hospital. It doesn't need to be used when you get out of the door of the hospital. Abbreviation: in class tag

class Car:
    element = ['iron']

    def __init__(self, color, logo):  # You must add self
        # Instance attribute, self is the object, object. Attribute = 'value'
        self.color = color
        self.logo = logo
        print('One Car Object is being generated')
        print('Perform the first step first: lower the chassis')
        print('Then perform the second step: install the frame')
        print('Then perform the third step: install the tire')
        print(f'Then proceed to step 4: paint color:{color}')
        print(f'Then perform step 5: printing{logo}logo')
        # Get class properties from class
        print(id(self.color))


# The process of creating an object through the template of class is the instantiation process
# The specific process, in the object of obtaining Car(), is actually in the automatic calling class__ init__ This function (initialization function) does not need to specify the function name
# What's the use of functions? You can specify the process of generating objects yourself
my_car = Car(color='red', logo='Porsche')
# Get class properties outside of class
# There are two ways to obtain instance properties:
# 1. In class, self.color
# 2. Class I_ car.color
print(my_car.color)  # If the class attribute color exists, self.color
# The values of the two methods of obtaining instance properties are equal. You can obtain the memory address through id() for comparison
print(id(my_car.color))

Operation results:

 

Keywords: Python

Added by procoder on Wed, 29 Sep 2021 03:28:03 +0300