#007 - python class

OOP: Object-Oriented Programming Object-Oriented Programming

A type consists of a collection of states (data) and a collection of actions that transform those states

kind:

  • Attributes
  • behavior (method)
  • Methods and variables:
    • Private: Internal use
    • public: externally visible

How to use objects to do really useful work?

  • There must be a way to ask an object to do something
  • Each object can only accept specific requests
    • The requests that can be sent to an object are defined by its "interface"
    • The "type" or "class" of an object specifies its interface

everything is an object

Object:

  • everything is an object
  • A program is a collection of objects
  • Each object has its own storage space and can hold other objects
    • By encapsulating existing objects, new types of objects can be made
  • Every object belongs to a certain type
  • All objects of the same class can receive the same message

Relationship between classes:

  • dependencies ("uses - a")
    • Methods of one class manipulate objects of another class
  • aggregate("has - a")
    • For example, there are integer objects, string objects, list objects in the a object... let's say a "has a " int, string object
  • Inherit("is - a")

Object-oriented programming principles:

  • Inheritance
    • The process by which an object obtains the properties of another object, used to implement the concept of classification by layers
    • A deeply inherited subclass inherits all properties of each of its ancestors in the class hierarchy
    • superclass, base class, parent class
    • Subclass, derived class (that is, it has the attributes of the parent class and has its own unique attributes)
  • package
    • Hide implementation details
    • A programming mechanism that binds code and processed data together to ensure that programs and data are protected from external interference and misuse
  • Polymorphism
    • The feature that an interface is used by multiple generic class actions, which action is used depends on the application
    • "One interface, many methods"
      • Used to design a common interface for a set of related actions to reduce program complexity

python classes and instances

  • instance initialization
    • Create an instance by calling the class
      • instance = ClassName(args…)
    • Classes can use two special methods init and del when instantiating
  • Create a class: use the class keyword
    • class ClassName(bases):
      • ‘’class documentation string’’
      • class_suite
    • A superclass is a collection of one or more parent classes for integration
    • A class body can contain: declaration statements, class member definitions, data attributes, methods
    • If there is no inheritance relationship, the "(bases)" after the ClassName can be omitted, and the class documentation is optional
    • A class is executable code, and the class object does not exist until it is run. After the class definition runs, the class class object is generated, and the class instance object is only after the class is instantiated. The two are different.
    • myinstance.method() = class.method(myinstance)
    • Python stipulates that no instance method is not allowed to be called, which is "binding"

Properties of Python classes and instances

  • The copy statement in the class statement will create class attributes, which are equivalent to static variables in java, resources shared by instance objects
  • Assigning to the special parameter self passed to the method in a class method creates an instance property
    • class MyClass():
      • gender = ''male'' class attribute
      • def setName(self, who):
        • self.name = who instance attribute

python constructor

  • When an instance is created, Python automatically calls the init method in the class to implicitly provide attributes to the instance
  • The init method is called the constructor
  • If there is no init method defined in the class, the instance is created as a simple namespace with only the name
  • class Animal:
  • name = 'someone' data attribute (member variable)
    • def init (self , voice = 'HI'): overloaded constructor
      • self.voice = voice
    • def del (self): overloaded destructor
      • pass
    • def saySomething(self): method attribute (member function)
      • print self.voice

Special attributes of the
class * You can use the dict dictionary attribute of the class or python's built-in dir() function to get the attributes of the class
* MyClass.__dict
* dir(MyClass)

Variables available in python class methods

  • Instance variables: specify the variable name and the instance itself for reference
    • self. variable name
  • Local variables: variables created inside the method, which can be used directly
  • Class variable (static variable): reference by specifying variable name and class name
    • class name.variable name
  • Global variables: use directly
  • Note: If there is a variable a in class A, create two objects A1 and A2 of class A. When creating A1 and A2, A1 and A2 will find the variable a in their own namespace. If they do not have it, they will climb up. tree, find the variable a in the namespace of class A, find and copy a copy to its own namespace, that is to say, the A1 and A2 objects have a copy of the variable a respectively

inherit:

  • Inheritance describes how accumulated properties are "inherited" to derived classes
    • A subclass can inherit any properties of its base class, including data properties and methods
    • A class without a specified base class defaults to a base class named object (for Python 3)
    • Python allows multiple inheritance
  • create subclass
    • When creating a subclass, simply follow the class name with a parent class or a parent class derived from it
    • class SubClassName(ParentClass1[,ParentClass2,…]):
      • ‘optional class documentation string’
      • class-suite
  • Contrast properties and methods
    • dir (ParentClass)
    • dir(ChildClass)
  • Tree climbing priority, bottom up
  • Inherited method specialization
    • Subclasses can completely replace properties inherited from superclasses
    • It is also possible to extend the methods of the superclass by calling back the superclass by the overridden method: ParClass.setInfo(self)

Built-in functions for classes, instances, and other objects

  • issubclass()
    • Boolean function to determine whether a class is derived from another class, syntax:
      • issubclass(sub,sup)
  • isinstance()
    • Boolean function that determines whether an object is an instance of a given class, syntax:
      • isinstance(obj1,class_obj2)
  • hasattr()
    • Boolean function to determine whether an object has the specified attribute, syntax:
      • hasattr(obj,’attr’)
    • Similar functions are getattr(), setattr() and delattr()
  • super()
    • Find its parent class in a word class so that its properties can be called
    • In general, only unbound methods can be used to call ancestor class methods
    • And super() can be used to pass in an instance or type object, syntax:
      • super(type[,obj])

operator overloading

  • Operator overloading refers to intercepting built-in operations in methods - when an instance of a class appears in a built-in operation, Python will automatically call the custom method and return the operation result of the custom method
    • Operator overloading lets classes intercept regular Python operations
      • Class to overload all Python expression operators
      • Classes can also overload built-in operations such as printing, function calls, and attribute dot operations.
    • Overloading makes an instance of a class behave like a built-in type
    • Overloading is achieved by providing a class method with a special name
  • Overloading is not necessary
  • Customize classes based on special methods

Note: Since Python 2.2, new-style classes have been introduced, which are divided into classic classes and new-style classes, but in Python 3, there are no classic classes!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325734606&siteId=291194637