Introduction and basic use of Python classes and object instances

Basic concepts of object-oriented technology

  • Class: used to describe a collection of objects with the same properties and methods. It defines the properties and methods common to every object in the collection. Objects are instances of classes. Simply put, a class is a template, and an instance is an object created based on the class

  • **Class variables:** Class variables are public throughout the instantiated object. Class variables are defined in the class and outside the function body. Class variables are generally not used as instance variables.

  • **Instance variables:** Variables defined in methods only act on the class of the current instance.

  • **Data members:** Class variables or instance variables are used to handle data related to the class and its instance objects.

  • **Method: **Function defined in the class.

  • **Instantiation:** Create an instance of a class, a specific object of the class.

  • **Object:** An instance of a data structure defined by a class. Objects include two data members (class variables and instance variables) and methods.

  • Encapsulation : Put multiple methods or properties into a private class, and this private class will not be accessed by other objects.

  • **Inheritance:** A derived class inherits the fields and methods of a base class.

    Inheritance allows an object of a derived class to be treated as a base class object. For example, there is such a design: an object of type Dog is derived from the Animal class, so Dog is also an Animal.

  • **Method rewriting:** If the method inherited from the parent class cannot meet the needs of the subclass, it can be rewritten. This process is called method override, also known as method rewriting.

  • Polymorphism : Different objects, calling the same method of the same class, show different forms.

Inheritance, encapsulation, and polymorphism are the three major characteristics of object-oriented. Classes can realize the three major characteristics of object-oriented.

Compared with other programming languages, Python adds class mechanisms without adding new syntax and semantics as much as possible.


Objects in Python

  • Objects are one of the most basic concepts in Python. In Python, everything can be an object.

    Python handles all data as objects, and assignment statements create objects and variables in memory.

  • Objects have three basic attributes: type, identity, and value

    print(type(500))	# 输出:<class 'int'>		# 对象的类型
    print(id(500))		# 输出:2556827724176		# 对象的身份标识
    print(500)			# 输出:500				# 对象的值
    

Class definition

Brief description

Although any variable in python can be called an object, the actual object is a specific instantiation of class attributes and methods. Only by using classes can you create a true object.

In Python, classes are defined through the class keyword, and the general convention for class names is to capitalize the first letter.

  • Define the basic format of a class:

    class 类名(父类):
       pass  # 此处可添加属性和方法
    
    class 类名:
       pass  # 此处可添加属性和方法
    

Note:

  • By default, all classes in Python3 implicitly inherit the object class. Therefore, in Python3, it is recommended that you do not need to explicitly inherit the object class.

  • Inner classes in python, python's inner classes can not only be defined in classes, but also in methods


Class attributes

Divided into two types: class attributes and instance attributes :

  • Class attributes : attributes bound to the class. There is one and only one copy . It is a common attribute that can be accessed by each instance.

    • Class attributes can be called directly through the class or through an instantiated object of the class, similar to static constants in Java

    • Note: Changing the value of a class attribute through the instantiation object of the class in python will not modify the value of the class variable!

      Because modifying the attributes of a class through an instance actually creates an instance attribute for the instance with the same name as the class attribute , and then modifies the instance attribute . The instance attribute access priority is higher than the class attribute , so the instance attribute is accessed first during access, which will block Remove access to class attributes

      class Person:
          name = 'aaa';
      
      person = Person()
      print(person.name)		# 输出:aaa
      
      person.name = "bbb"
      print(person.name)		# 输出:bbb
      print(Person.name)		# 输出:aaa
      
      del person.name			# 可以使用 del 删除与类属性同名的实例属性
      print(person.name)		# 输出:aaa
      
  • Instance attributes : each instance has its own and is independent of each other

    Access instance properties:

    • Inside the instance method, pass "self.property name"
    • Outside the class, access indirectly by calling instance methods

    **Private instance properties:** The property name starts with an underscore ( _private_attrs), indicating that the property is declared private and cannot be used or directly accessed outside the class. The way to use it in a method inside a class is:self._private_attrs


class methods

Within a class, use the def keyword to define functions. Functions defined in a class are also called methods.

  • Class methods :

    In python, a class method is a method decorated by the decorator @classmethod , indicating that it is a class method

    The first parameter of the class method is cls , which represents the class itself. This allows class methods to access and modify class properties and other class methods.

    Class methods can be called directly through the class or through an instantiated object of the class (not recommended)

    Subclass inheritance: Subclasses can inherit and override class methods of the parent class.

  • Instance method :

    Unlike general function definitions, the first formal parameter of an instance method must be self. The meaning of self here refers to the instantiated object.

    Note: self is not a keyword in Python, so the first formal parameter of the instance method can actually be named by another name, but industry practice is to name it self.

    Call instance method:

    • Inside the instance method, pass "self.methodname()"
    • Outside the class, pass "object name.Instance method name (except self parameters)"
  • Static method:

    Decorator: Static methods are defined using the @staticmethod decorator.

    Parameters: Static methods have no special parameters and do not require a reference to the class itself or an instance. They are similar to normal functions.

    Cannot access class properties and methods: Static methods cannot directly access class properties and methods because they do not pass a class or instance as a parameter.

    Instantiating the object is not required: static methods can be called from the class itself without instantiating the object. For example, MyClass.my_static_method()

    No inheritance by subclasses: Static methods are not inherited by subclasses because they are not associated with the class or instance.

    Common scenarios: Static methods are typically used for operations that are related to the class but not to a specific instance, such as utility functions or helper functions.

  • Private method :

    A method starting with two underscores ( __private_method) indicates that the method is declared as a private method and cannot be called outside the class.

    The calling method inside the class is:slef.__private_methods


special functions of class

There are mainly the following types:

  • __init__(Initialization function): It is automatically called when calling a class to create an object to complete the initialization of the object.

    The initialization function in python does not support method overloading. There is only one

    In Python, **mapthe initialization function can be defined as a flexible multi-parameter transfer

    class TestClassA:
         def __init__(self, a, b):
             print("我是python的构造方法");
    
    class TestClassB:
        #定义灵活的可传递任何数据的构造方法
        def __init__(self, **map):
            print("我是python的构造方法" + map.get("name"));
            print("我是python的构造方法" + map.get("age"));
    

    Extension: __init__The usage of the method is similar to the constructor method in Java, but it is not a constructor method. The method of creating an instance in Python is __new__. This method is mostly used by default in Python and generally does not need to be redefined.

  • __del__(Destructor): Will be automatically called when the object is recycled

    Both the constructor and the destructor need not be written when defining the class.


Class inheritance

  • Single inheritance

    grammar:

    class <类名>(父类名)
    	<语句>
    

    Example:

    class Student(people):
            grade = ''
            def __init__(self,n,a,w,g):
                #调用父类的构函
                people.__init__(self,n,a,w)
                self.grade = g
            #覆写父类的方法
            def speak(self):
                print("%s is speaking: I am %d years old,and I am in grade %d"%(self.name,self.age,self.grade))
    
        s = Student('ken',20,60,3)
        s.speak()
    
  • Multiple inheritance of classes

    grammar:

    class 类名(父类1, 父类2, ...., 父类n)
    	<语句1>
    

    Note: the order of parent classes in parentheses. If there is the same method name in the parent class, but it is not specified when using it in the subclass, Python searches from left to right, that is, when the method is not found in the subclass, it searches from left to right to see if the method is included in the parent class .

Guess you like

Origin blog.csdn.net/footless_bird/article/details/133251787