Explanation of knowledge about Python automated testing, objects, attributes and methods

I. Introduction

Hello everyone, the author brings you another article. This article mainly explains the knowledge points of classes, objects, attributes and methods in python. Let’s start directly without talking nonsense.

2. Knowledge collection

2.1 Class and Object Basics

2.1.1 Overview of classes and objects

Class: Class is a general term for things with common characteristics and common behaviors. Things gather together and people are divided into groups. This can be well reflected here. Chickens and ducks can be classified as poultry, and kittens and dogs can also be classified as pets. , Lamborghini, Bugatti Veyron can be divided into sports car category, etc., as long as they have the same characteristics or behaviors, they can be divided into one category.

Classes are often very broad. For example, there are many sports cars in the sports car class. So, can two sports cars and one sports car be a class? In fact, it is also possible. Two sports cars have common characteristics and characteristics. We can call them Class, when there is only one sports car, it can also be called a class, it may be a wonderful class, or it may be a legendary class, such as the rumored: golden sports car, which has reached the highest in the world, has unique or special features, and can also be Separately become a class, we call this situation a singleton.

Object: An object is a member of a type of transaction, a single individual, and an object is also called an instance. To put it more plainly, an object is a member of a class, and there are many sports cars in the sports car class, so one of the cars is a member, that is, an object, an instance.

2.1.2 A simple class and object

A simple class and object looks like this:

"""
格式为:
class Car():
	类主体
"""
class Car():
    pass
 
print(Car)  # 类
print(Car())  # 对象

2.1.3 Class naming convention

The naming of classes is different from that of variables, functions, modules, and packages. Generally speaking, variables, functions, etc. are named in snake form, also known as underscore naming, while classes are mainly named in camel case:

"""
蛇形命名,单词使用下划线拼接,全部为小写
"""
add_number
str_add
number_add_no1_with
 
"""
驼峰命名,单词拼接,首字母大写
"""
class AutoCar:
    pass
 
class NumberAdd:
    pass
 
class CaseTest:
    pass

 2.1.4 Another representation of classes and objects

In addition to the above-mentioned printing, we can also assign a class or object to a variable, and then get the class or object by printing the variable. It can be assigned not only to one, but also to different multiple variables, and it is independent. Objects from The difference can be seen from the different memory addresses:

class Car:
    pass
 
demo1_class = Car
demo2_class = Car()
demo3_class = Car()
print(demo1_class)
print(demo2_class)
print(demo3_class)

 

2.2 Explanation of attributes and methods

2.2.1 Class attributes

A class is a general term for things with common characteristics and common behaviors. Attributes represent certain characteristics of a class or object, and the characteristics of a class are called class attributes. For example, the common characteristics of a car class have steering wheels, Both have wheels and so on, then these are the class attributes:

Now that we have class attributes, we can also get a class attribute by class name. attribute:

class Car:
    """类属性"""
    steering_wheel = True  # 方向盘
    tyre_number = 4  # 车轮个数
    engine = True  # 发动机
    material = ["铁", "橡胶", "玻璃", "塑料", "铝合金"]  # 材料
 
"""获取类属性"""
print(Car.steering_wheel)
print(Car.tyre_number)
print(Car.engine)
print(Car.material)

 

Class attributes are the same as functions, they are independent and do not affect each other with global variables:

class Car:
    tyre_number = 4  # 车轮个数
 
tyre_number = 5
print(Car.tyre_number)
print(tyre_number)

 

We can also obtain class attributes through objects. In addition, we can also modify a class attribute, but we can only modify class attributes through classes, not objects:

class Car:
    tyre_number = 4  # 车轮个数
 
my_car = Car()
print(my_car.tyre_number)
 
 
"""修改类属性"""
Car.tyre_number = 3
print(f"修改后的轮子数量是:{Car.tyre_number}")
"""新增属性"""
Car.steering_wheel = True
print(Car.steering_wheel)

 

2.2.2 Definition of class attributes

In addition to being defined in the class, class attributes can also be defined globally:

class Car:
    pass
 
 
# 全局中定义类属性
Car.wheel = True
print(Car.wheel)

2.2.3 Instance method calls

The method is the behavior of the class, using the syntax of the function, the method is a function, the method has a fixed parameter self, the method can be customized, self represents the instance, the object. If I want to call a method, as shown in the following code, this form is also called an instance method :

"""
实例方法:通过对象.方法()进行调用
"""
class Car:
    """方法"""
    def drive(self):
        print("滴滴,开始开车")
 
 
# 调用方法
my_car = Car()
my_car.drive()

 

2.2.4 Class method call

Class methods are invoked through class.method(). A class method is represented as a decorator as @classmethod, and self is replaced by cls, which is represented as a class method:

"""
类方法:通过类.方法()进行调用
"""
class Car:
    pass
 
    @classmethod
    def color(cls):
        my_color = "我是红色,一个类方法"
        return my_color
 
 
print(Car.color())

 2.2.5 Static method calls

Static methods are similar to class methods. Static methods also need decorators. Static methods have no fixed parameters. Static method decorators are represented as @staticmethod. Both static method classes and instances can be called. Static methods and classes and objects have no directness. Relationships can be defined outside of class management:

class Car:
    pass
 
 
    """静态方法"""
    @staticmethod
    def color():
        color = "绿色,我是静态方法"
        return color
 
 
print(Car.color())

 

2.2.6 Method Inheritance

Methods can be inherited, just like a son inherits his father’s property, then he can use his father’s property at will. If class A inherits class B, then the same class A can use all methods and objects of class B:

class Car:
 
    def driver(self):
        print("开车")
    def stop(self):
        print("停车")
 
 
"""
继承
Car:父类
SuperCar:子类
子类可以使用父类所有的属性和方法
"""
class SuperCar(Car):
    """所有Car的属性和行为,SuperCar全部继承"""
    pass
 
 
Ferrari = SuperCar()
Ferrari.driver()

 

2.2.7 Method rewriting

When the subclass and the parent class use the same name method, their own method is used first. We call this method rewriting:

class Car:
 
    def driver(self):
        print("开车")
    def stop(self):
        print("停车")
 
 
"""
继承
Car:父类
SuperCar:子类
子类可以使用父类所有的属性和方法
"""
class SuperCar(Car):
    """所有Car的属性和行为,SuperCar全部继承"""
    def driver(self):
        print("跑车开起来飞快")
 
 
 
Ferrari = SuperCar()
Ferrari.driver()

 

2.2.8 Super Rewrite

When the subclass and the parent class use the method with the same name, it will use its own first, and we can also have our own and the parent class at the same time. In this case, we call it super rewriting:

class Car:
 
    def driver(self):
        print("开车")
    def stop(self):
        print("停车")
 
 
"""
继承
Car:父类
SuperCar:子类
子类可以使用父类所有的属性和方法
"""
class SuperCar(Car):
    """所有Car的属性和行为,SuperCar全部继承"""
    def driver(self):
        """超级重写,super()代表父类"""
        super().driver()
        print("跑车开起来飞快")
 
 
 
Ferrari = SuperCar()
Ferrari.driver()

 

2.3 Explanation of object initialization and instance attributes

2.3.1 Object initialization

Creating an object from scratch is a production process. After producing an object, we call this situation the initialization of the object, and the initialized object will automatically call the magic function init under the class, which we execute when printing the object The code segment in the magic function, the self in the function represents the mark before an object is generated, and after the generation, it is assigned to object1 as shown in the following code:

class Car:
    tyre_number = 4  # 车轮个数
    def __init__(self):
        print("I love you")
 
 
object1 = Car()  # 我们把Car()的产生称之为对象初始化
 
print(object1)

 

The init function is different from ordinary functions. The init function cannot have a return value. The default is None and cannot be other, otherwise an error will be reported:

class Car:
    wheel = True
 
    def __init__(self):
        self.wheel = True
        return "a"
 
 
print(Car().wheel)

2.3.2 Class attributes and instance attributes

First of all, a concept must be clarified. Instance attributes are object attributes, and objects are instances. Instance attributes represent members, individual attributes and unique attributes of objects, while class attributes are common attributes and characteristics that everyone has.

An instance attribute looks like this:

class Car:
    tyre_number = 4  # 类属性
    def __init__(self):
        """实例属性,self.对象属性"""
        self.color = "红色"  # 实例属性
        self.price = "190w"

 If the name of the class attribute and the instance attribute are the same, then the instance attribute will use its own first, and we can also use positional parameters to improve convenience:

class Car:
    tyre_number = 4  # 车轮个数
    def __init__(self, car_color, car_price):
        """实例属性,self.对象属性"""
        self.color = car_color
        self.price = car_price
 
 
my_car = Car("黄金色", "3500w")
 
print(f"这台车的颜色是{my_car.color}")
print(f"这台车的价格是{my_car.price}")

 

2.4 Object assignment

Objects are different from classes. The assignments of objects are not equal, but the assignments of classes are equal. As shown in the following code, the class is assigned to 3 variables, which are exactly the same memory address, which proves that these 3 variables all represent the same 1 class, but the object assignments are at different memory addresses, so it can be known that the three variables assigned by the object are different objects:

class Car:
    pass
 
 
my_car1 = Car
my_car2 = Car
my_car3 = Car
my_obj1_car = Car()
my_obj2_car = Car()
my_obj3_car = Car()
 
print(id(my_car1))
print(id(my_car2))
print(id(my_car3))
print(my_obj1_car)
print(my_obj2_car)
print(my_obj3_car)

 

2.4.1 Access to class attributes and instance attributes

If we want to access a class attribute, we can get it through the class or object:

class Car:
    wheel = True
print(Car.wheel)
print(Car().wheel)

 

2.5 The role of classes and objects

Classes, objects, and functions are similar. They are called and called. Why do we need to learn classes and objects? What are the benefits? In fact, there is not much difference in essence. The obvious thing is that classes are more convenient to manage and more concise when calling , we can accept the complexity of the definition, but we cannot accept the complexity of the call, because there is only one definition, and there are countless calls. If there are 100 formal parameters in a function, then we need to pass 100 actual parameters when calling the function, but In the class, we can define 100 instance attributes at one go, thereby simplifying the calling process, and can pass fewer parameters or even no parameters when calling. Although functions can also be written as default parameters and keyword parameters, the readability is not high. It will not be as clear and direct as a class, which is the most direct reason we use classes and objects.

Classes and objects are just more concise than the calling process of functions. This does not mean that we must use classes and objects in real projects. We can also use functions to achieve the same functions, as small as a script, as large as When it comes to a test framework, there will not be a big difference in the amount of code reduced by classes and objects. In terms of efficiency, the methods of classes and objects are no different from functions, but we still need to learn, because it is more convenient to call and understand The cost will also be relatively reduced.

Finally, I would like to thank everyone who has read my article carefully. Reciprocity is always necessary. Although it is not a very valuable thing, you can take it away if you need it:

insert image description here

Software testing interview applet

The software test question bank maxed out by millions of people! ! ! Who is who knows! ! ! The most comprehensive quiz mini program on the whole network, you can use your mobile phone to do the quizzes, on the subway or on the bus, roll it up!

The following interview question sections are covered:

1. Basic theory of software testing, 2. web, app, interface function testing, 3. network, 4. database, 5. linux

6. web, app, interface automation, 7. performance testing, 8. programming basics, 9. hr interview questions, 10. open test questions, 11. security testing, 12. computer basics

These materials should be the most comprehensive and complete preparation warehouse for [software testing] friends. This warehouse has also accompanied tens of thousands of test engineers through the most difficult journey. I hope it can help you too!      

Guess you like

Origin blog.csdn.net/nhb687095/article/details/132451895
Recommended