Python Core Notes for Test Development (18): Introduction to Classes and Objects

Python is an object-oriented programming language. The two most fundamental concepts in object-oriented programming are classes and objects. A class is a template for a group of objects of a class with the same properties and functions, and objects are generated after the class is instantiated. Creating a class and object in Python is easy.

18.1 Defining a class

Use the class statement to create a new class, followed by the class name and ending with a colon, usually with a capital letter:
the following is an example of a class:

class Document:
	"""
    这是一个文档字符串
    """
    # 类变量
    WELCOME_STR = 'Welcome! The context for this book is {}.'

    # 初始化函数,对创建的对象进行初始化,第一个参数是self,不能有返回值
    def __init__(self, title, author, context):
        print('init function called')
        self.title = title  # 成员变量
        self.author = author # 成员变量
        self.__context = context # 成员变量

    # 类函数,常用来实现不同的初始化函数
    @classmethod
    def create_empty_book(cls, title, author):  # 第一参数是cls
    	print(cls.WELCOME_STR)
        return cls(title=title, author=author, context='nothing')

    # 成员函数,第一个参数必须是self
    def get_context_length(self): 
        return len(self.__context)

    # 静态函数,通常用在类内其他函数中。
    @staticmethod
    def get_welcome(context):
        return Document.WELCOME_STR.format(context)

You can recognize this class from the following aspects:

  1. The class name is Document, and for Python3, all classes inherit from the object class by default.
  2. There is a class variable WELCOME_STR that is common to all instantiated objects. Can be accessed using Document.WELCOME_STR in inner or outer classes. Class variables are defined inside the class and outside the function body.
  3. __init__It is an initialization function, which is called immediately after an instance of this class is created to initialize the instance.
  4. selfRepresents an instance of this class that must be the first parameter of all instance methods self.
  5. __init__is the initialization function, which selfsets three instance properties for the instance object, namely title, authorand __context. Instance properties are related to specific objects of the class, each object has its own properties, and is not shared by all objects like class variables.
  6. get_context_lengthis a member method of the class and its first parameter must be self. Class variables can be accessed, and member methods are usually called through the instantiated object. Of course, it is also possible to call with the class name, but an object object must be passed in.
  7. create_empty_bookis a class method of the class, identified with @classmethod, its first parameter must be cls. Class methods can access class variables and are usually called by the class name.
  8. get_welcomeIt is a static method of the class, it is designed to be used in other functions inside the class, but it can also be called by the class name and instance object outside the class.

18.2 Instantiating a class

In other programming languages, instantiated classes generally use the keyword new, such as the Java language. But there is no such keyword in Python. The instantiation of a class is similar to calling a function. The class name is enclosed in parentheses, and inside the parentheses are the attribute values ​​of the class.

The following is instantiated with the class name Document and receives properties through the __init__method .

d=Document("demo", "chunming", "show you class")

The above statement actually performs two steps in Python:

  1. Call __new__the method to create an instance object.

The above class has no __new__methods. Generally, there is no need to define it yourself. By default, Python calls the method of the direct parent class of the class __new__to construct an instance of the class. If the parent class of the class has no __new__method, it will always be traced back to the method of object according to this rule __new__. The direct parent class of the Document class is object, so when the Document class is instantiated, the __new__method of the object class is called. See how the methods of object __new__are defined:

@staticmethod # known case of __new__
def __new__(cls, *more): # known special case of object.__new__
    """ Create and return a new object.  See help(type) for accurate signature. """
    pass

The method of visible object __new__is a static method, usually used asobject.__new__。

  1. Then use the __init__method to initialize the object. If not defined, no special initialization action will be performed.

18.3 Accessing properties and methods

After instantiating a class, you can use the object to access class variables, instance properties, class methods, instance methods, and static methods.
In the above class code file, write the following test code:

if __name__ == '__main__':
    d = Document("demo", "chunming", "show you class")
    print("访问类变量=", d.WELCOME_STR)  # 1.实例对象访问类变量
    d0 = d.create_empty_book("有默认content", "实例对象")  # 2.实例对象调用类方法
    print(d.get_welcome("实例对象调用静态函数"))  # 3. 实例对象调用静态方法
    print(d.get_context_length())  # 4. 实例对象调用成员方法

    print(Document.WELCOME_STR)  # 5. 类名访问类变量
    # print(Document.title)  # 不可以。
    print(Document.get_context_length(d))  # 6. 类名访问成员方法
    f = Document.create_empty_book("static", "liu")  # 7. 类名访问类方法
    print(Document.get_welcome("aa"))  # 8. 类名访问静态方法

You can access the properties and methods of the class, all through dots. Both instance objects and classes have access to class variables, class methods, instance methods, and static methods. But classes cannot access instance properties.

18.4 How to see what properties and methods a class has

There are two ways to see what properties a class has.

  • The first method, dir(classname), displays a list of property names.
['WELCOME_STR', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'create_empty_book', 'get_context_length', 'get_welcome']
  • The second method, classname. __dict__, is a dictionary containing the names and values ​​of the attributes
{'__module__': '__main__', '__doc__': '\n    这是一个文档字符串\n    ', 'WELCOME_STR': 'Welcome! The context for this book is {}.', '__init__': <function Document.__init__ at 0x1101f9f80>, 'create_empty_book': <classmethod object at 0x110260750>, 'get_context_length': <function Document.get_context_length at 0x11025d710>, 'get_welcome': <staticmethod object at 0x110260790>, '__dict__': <attribute '__dict__' of 'Document' objects>, '__weakref__': <attribute '__weakref__' of 'Document' objects>}

As can be seen from the output of the dir function and __dict__, there are some attributes that we have not defined in the Document class, such as __module__, __class__, __dict__and __doc__so on. These attributes are automatically set by Python for each class.

  • C.__name__, representing the name of class C
  • C.__dict__, representing the properties and values ​​of class C.
  • C.__module__, indicating the name of the module where the definition of class C is located, or a string when running the module independently __main__. When the module is imported, it is set to the name of the module.
  • i.__class__, indicating the class to which instance i belongs
  • C.__bases__, which represents a tuple of all direct parent classes of class C, excluding the parent class of the parent class
  • C.__doc__, representing the docstring for class C.

18.5 Methods in Classes

  • Construction method
  1. __init__Represents a constructor, which initializes the generated object, and a function that will be automatically called after an object is generated.
  • member method
  1. A certain dynamic capability of the object, such as the get_context_length function in the above code, the first parameter of the function is self.
  • static method
  1. @staticmethodAdd the representation on the line before the function
  2. Static methods have nothing to do with classes, are used to complete some tasks individually, and can be used in multiple member methods.
  • class method
  1. The first parameter is generally cls, indicating that a class must be passed in. A decorator is @classmethodrequired to declare.
  2. A common scenario is to implement different __init__constructors. For example, in the above code, we use the create_empty_book class function to create a new book object, and the context of the book created by it must be 'nothing'.

All right. Getting started with Python classes and objects is introduced here. In the next subsection, we continue to introduce the input of attributes.

Guess you like

Origin blog.csdn.net/liuchunming033/article/details/107909058