Python object-oriented (class, inheritance of class)

Python Object Oriented

Remember one sentence: Classes are templates, while instances are objects created from classes.

Class is literally understood in the beginning of school. It can be unilaterally thought to be a kind. It is a sampling of similar characteristics, that is, something similar, which can abstract similar characteristics of transactions into a class.(Transactions can be specific objects or behaviors)

For example, a circle is an attribute with two similar characteristics: pi and r.A circle class is abstracted based on similar characteristics. The radius of each circle can be different, then the radius can be used as an instance attribute of the circle. If the pi of each circle is the same, then the pi of the circle can be used as a class attribute, thus defining a circle class.And we need to know the area, perimeter and so on of the circle can be calculated by the class method.

(Read the whole article or don't understand the classes. Look back at this section to understand more about columns.)

Scenarios for classes:

Scattered Code (Code Block)-->Function (Method)-->Class-->Module (File)
Class: Things that represent abstraction (obscurity)
Object: Things that are specific (clear)

1. Introduction to Object-Oriented Technology

  • Class: A collection of objects that describe the same properties and methods.It defines the properties and methods common to each object in the collection.Objects are instances of classes.
  • Class variables: Class variables are common throughout the instantiated object.Class variables are defined in the class and outside the body of the function.Class variables are usually not used as instance variables.
  • Data member: A class variable or instance variable used to process data about a class and its instance objects.
  • Method override: If a method inherited from a parent does not meet the needs of a subclass, it can be overridden. This process is called method override, also known as method override.
  • Local variable: A variable defined in a method that only acts on the class of the current instance.
  • Instance variables: In a class declaration, attributes are represented as variables.This variable is called an instance variable and is declared inside the class declaration but outside the other member methods of the class.
  • Inheritance: A derived class inherits the fields and methods of a base class.Inheritance also allows objects of a derived class to be treated as a base class object.For example, there is a design where an object of type Dog derives from the Animal class, which simulates an "is-a" relationship (for example, Dog is an Animal).
  • Instantiation: Create an instance of a class, a specific object of the class.
  • Method: Function defined in class.
  • Object: An instance of a data structure defined by a class.The object consists of two data members (class variable and instance variable) and methods.

2. Create Classes

Use the class statement to create a new class followed by the name of the class and ending with a colon:

class ClassName:
   'Help information for classes'   #Class Document String
   class_suite  #Class Body

Class help information can be viewed through ClassName.doc.

class_suite consists of class members, methods, and data attributes.

(1) Examples

Files describing human beings
Class structure:
1. Dynamic behaviors (verbs): speak, sing
2. Static attributes (nouns): gender, user_name
(1) Global: can be used anywhere in a class
(2) Local: can only be used within methods
Use Class:
Instantiate object: object name = class name (parameter [optional])

class Human():
    """Simulate human"""
    def __init__(self, sex, name):
        """Initialization properties: gender and user_name"""
        self.gender = sex
        self.user_name = name

    def speak(self):
        """Simulate human speech"""
        print(self.user_name.title() + "Talking.")

    def sing(self):
        """Simulate human singing"""
        print(self.user_name.title() + "Singing.")
  • The empCount variable is a class variable whose value will be shared among all instances of this class.You can use Employee.empCount to access both internal and external classes.
  • The first method, the u init_(), is a special method called the constructor or initialization method of a class, which is called when an instance of the class is created
  • self represents an instance of a class and is required to define its methods, although it is not necessary to pass in parameters when calling.
The output is as follows:
# Using classes
man = Human('male','xgp')
man.speak()

lz = Human('male','kk')
lz.sing()

(2) Modify the initial value

class Pet():

    def __init__(self,sex,strain):
        """Assign attributes initial values (default values)"""
        self.nick_name = 'Imida'
        self.gender = sex
        self.stain = strain

cat = Pet('common','Groundcat')
# Modify Initial Value
cat.nick_name = 'Wonderful'
print(cat.nick_name)
The output is as follows:
Wonderful

3. self represents an instance of a class, not a class

Classes'methods differ only from ordinary functions in that they must have an additional first parameter name, which by convention is self.

class Test:
    def prt(self):
        print(self)
        print(self.__class__)

t = Test()
t.prt()
The output is as follows:
<__main__.Test instance at 0x10d066878>
__main__.Test

It is clear from the execution that self represents an instance of the class, represents the address of the current object, and self. u class_ points to the class.

self is not a python keyword, so we can change it to runoob as well:

class Test:
    def prt(runoob):
        print(runoob)
        print(runoob.__class__)

t = Test()
t.prt()
The output is as follows:
<__main__.Test instance at 0x10d066878>
__main__.Test

4. Create instance objects

The new keyword is commonly used in other programming languages for instantiating classes, but it is not available in Python. Instantiating classes is similar to calling functions.

The following is instantiated using the name Dn of the class and receives parameters through the u init_u method.

"""
//Xiao Ming and Xiao Hong each bought a notebook computer.
//One of the nickname computer brands is Lenovo, CPU8 Core, 512G Solid State Hard Disk, Double Swift Mouse
//The brand of Jiuhong's computer is Machine, CPU4 Core, 256G Solid State Hard Disk + 1T Normal Hard Disk, Machine Mouse
//Using object-oriented thinking, write code to complete the above description.
"""
class Dn():

    def __init__(self,name,brand,cpu,disk,mouse):
        self.nice_name = name
        self.nice_pp = brand
        self.nice_cpu = cpu
        self.nice_disk = disk
        self.nice_mouse = mouse
    def xgp(self):
        print(self.nice_name + 'Computer Configuration:'
              + 'Brand:' + self.nice_pp + ','
              + 'cpu: ' +self.nice_cpu + ','
              + 'Hard Disk:' +self.nice_disk + ','
              + 'Mouse:' + self.nice_mouse + ','
              + '". ')
# You can use dots. to access the properties of an object.Access class variables using the name of the following class
Dn1 = Dn('Pet name','association','8 nucleus','512 Solid State Hard Disk','Double Swallow')
Dn1.xgp()

Dn2 = Dn('millet','Machinist','4 nucleus','256G Solid State Hard Disk+1T Normal Hard Disk','Mechanical Mouse')
Dn2.xgp()
The output is as follows:
Small name computer configuration: "Brand: Lenovo, cpu:8 core, solid state hard disk: 512 solid state hard disk, mouse: double swallow".
Small name computer configuration: "Brand: machinist, cpu:4 core, solid state hard disk: 256G solid state hard disk, mechanical hard disk 1T normal hard disk, mouse: machinist mouse".

5. Inheritance of Classes

One of the main benefits of object-oriented programming is code reuse, which is achieved through inheritance mechanisms.

New classes created by inheritance are called subclasses or derived classes, and inherited classes are called base classes, parent classes, or superclasses.

Inheritance Grammar

Class derived class name (base class name)
    ...

Some features of inheritance in python:

  • 1. If a parent class's construction method is required in a subclass, it needs to be displayed that calls the parent class's construction method, or does not override the parent class's construction method.Detailed instructions can be viewed: python subclass inherits parent constructor description.
  • 2. When calling a method of a base class, the class name of the base class needs to be prefixed with the self parameter variable.The difference is that you do not need to take a self parameter when calling a normal function in a class
  • 3. Python always finds the method of the corresponding type first. If it cannot find the corresponding method in the derived class, it begins to look in the base class one by one.(Find the method invoked in this class first, not in the base class until it is not found).

If more than one class is listed in the inheritance tuple, it is called multiple inheritance.

Grammar:

A declaration of a derived class, similar to their parent class, follows the class name in the list of inherited base classes as follows:

class SubClassName (ParentClass1[, ParentClass2, ...]):
    ...

(1) Examples

class Parent:        # Define Parent Class
   parentAttr = 100
   def __init__(self):
      print ("Call parent class constructor")

   def parentMethod(self):
      print('Call parent method')

   def setAttr(self, attr):
      Parent.parentAttr = attr

   def getAttr(self):
      print ("Parent Properties :", Parent.parentAttr)

class Child(Parent): # Define subclasses
   def __init__(self):
      print ("Call subclass construction method")

   def childMethod(self):
      print ('Call subclass methods')

c = Child()          # Instantiate Subclass
c.childMethod()      # Calling methods of subclasses
c.parentMethod()     # Call parent method
c.setAttr(200)       # Call the parent class's method again - set the property value
c.getAttr()          # Call the parent class's method again - get the property value
The output is as follows:
Call subclass construction method
 Call subclass methods
 Call parent method
 Parent attribute: 200

(2) Examples

"""
//Xiao Ming and Xiao Hong each bought a notebook computer.
//One of the nickname computer brands is Lenovo, CPU8 Core, 512G Solid State Hard Disk, Double Swift Mouse
//The brand of Jiuhong's computer is Machine, CPU4 Core, 256G Solid State Hard Disk + 1T Normal Hard Disk, Machine Mouse
//Using object-oriented thinking, write code to complete the above description.
"""
class Dn():

    def __init__(self,brand,cpu,disk,mouse):
        self.nice_pp = brand
        self.nice_cpu = cpu
        self.nice_disk = disk
        self.nice_mouse = mouse

# Inheritance: Share code for a class
class XiaoMing(Dn):

    def __init__(self,brand,cpu,disk,mouse):
        super().__init__(brand,cpu,disk,mouse)

    def xgp(self,name):
        print(name + 'Computer Configuration:'
                      + 'Brand:' + self.nice_pp + ','
                      + 'cpu: ' +self.nice_cpu + ','
                      + 'Solid state hard disk:' +self.nice_disk + ','
                      + 'Mouse:' + self.nice_mouse
                      + '". ')
class XiaoHong(Dn):
    def __init__(self,brand,cpu,disk,sim_disk,mouse):
        self.sim_disk = sim_disk
        super() . __init__(brand,cpu,disk,mouse)

    def wsd(self,name):
        print(name + 'Computer Configuration:'
              + 'Brand:' + self.nice_pp + ','
              + 'cpu: ' + self.nice_cpu + ','
              + 'Solid state hard disk:' + self.nice_disk + ','
              + 'Mechanical hard disk' + self.sim_disk + ','
              + 'Mouse:' + self.nice_mouse
              + '". ')

xiaoming = XiaoMing('association','8 nucleus','512 Solid State Hard Disk','Double Swallow')
xiaoming.xgp('Pet name')
xiaohong = XiaoHong('Machinist','4 nucleus','256G Solid State Hard Disk','1T Normal Hard Disk','Mechanical Mouse')
xiaohong.wsd('Pet name')
The output is as follows:
Small name computer configuration: "Brand: Lenovo, cpu:8 core, solid state hard disk: 512 solid state hard disk, mouse: double swallow".
Small name computer configuration: "Brand: machinist, cpu:4 core, solid state hard disk: 256G solid state hard disk, mechanical hard disk 1T normal hard disk, mouse: machinist mouse".

6. Summary

Transfer Diagram of Parameters, Translation and pythoncentral network

  • In 1 and 2, the arguments are passed to the method.
  • The 1 and 2 parameters are passed to the data parameter in the init method.
  • On 3, the self argument refers to the instance.
  • 3**The self parameter points to the current instance itself, and self represents the instance variable ik1 or Kls('arun') created.**
  • At 4, we do not need to provide the instance to the method, as it is handled by the interpretor itself.
  • 4We don't need to pass the instance itself to the method; the Python interpreter does it; ik14 is automatically passed into the method as the first instance parameter (self).

Tags: Python Attribute Programming Swift

Posted on Thu, 26 Mar 2020 11:21:52 -0700 by redhair