Comparison of python vs golang # method and polymorphism # in use

1, # method # comparison of the use of two languages

1.1 python:

Because python supports object-oriented programming, we can first define classes, bind attributes (data) in classes, and then use data encapsulation (define functions to access data), that is, class methods. Finally, the use of the method is realized after instantiation.

  • Define the Person class
  • Bind firstname and lastname attributes
  • Define the function printme in the class and print firstname and lastname
  • After instantiation, the printme method is called.

 

#Inherit object class by default
class Person(object):    
#Pass__ init__ Method forces the binding of necessary properties, and self represents the creation of the instance itself
    def __init__(self,firstname,lastname):    
        self.firstname=firstname
        self.lastname=lastname
    def printme(self):
        print("person name: "+self.firstname+" "+self.lastname)
 #Initialize the instance and call the method
p=Person('michael','hu')   
p.printme()

[python code 1]

1.2 golang:

Because golang has no class concept, object-oriented methods cannot be used. Therefore, first define the structure (which can be understood as a set of data attributes bound through init in python), and then define the method (there are more receivers than the function)

  • Define the structure Person, including firstname and LastName attributes
  • Define the Print method, and the incoming recipient is a Person type pointer
  • The variable is initialized with the structure, and the variable uses the Print method
package main
import "fmt"

 //Custom Person structure
type Person struct{   
    firstname string
    lastname string
}
 //(p *Person) is the receiver of the Print method. The p name can be defined as self in python. P is usually defined as a pointer to save memory
func (p *Person) Printme() { 
    fmt.Println("person name is :",p.firstname,p.lastname)
}

func main(){
    //Initialize p with the structure Person, where the address is passed
    p:=&Person{firstname:"michael",lastname:"hu",} 
    //When the Print method is called, the pointer p will be dereferenced automatically   
    p.Printme()
}

[golang code 1]

Summary:

python instantiates the class first, and then calls the instantiated method
golang is a method of instantiating a structure first and then using the same instance

2, python polymorphism and golang polymorphism

2.1 python:

Subclasses can inherit the main class, and subclasses can reuse the main class methods, add methods or rewrite methods. Calling the main class or subclass respectively can implement the corresponding methods, but there is no need to call them repeatedly. Using polymorphism is to use a unified interface to call the methods of these classes. The interface here is to define a function,
How to use polymorphism:

  • First define a function whose parameters are classes
  • Instantiate, pass in the class, and use the method. When the passed in parameter is the main class or its subclass, the function will call the method of the corresponding main class or subclass according to the corresponding class type (the class type can be understood as the data type encapsulated by class).

Continue to add the following in [python code 1]:

#Define the subclass Animal, inherit from the Person class, rewrite the print method, and change the binding attribute here
class Animal(Person):
    def __init__(self,animals,sex):
        self.animals=animals
        self.sex=sex
    def printme(self):
        print(f'animal type is: {self.animals}, sex is:{self.sex}')

#Define the function showme as a polymorphic interface and call different class methods according to the incoming class
def showme(livers):
    livers.printme()

#Pass in the Person class and call the methods in the Person class
showme(Person('michael','hu'))
#Return person name: michael hu

#Pass in the Animal subclass and call the methods in the Animal class
showme(Animal('cat','male'))
#Return animal type is: cat, sex is:male

[python code 2]

  • Duck type: if the defined class does not inherit from the main class, as long as the functions in the class use the same name. You can use polymorphism.

Continue to add the following in [python code 2]:

2.2 golang

The polymorphic feature of golang is implemented by the interface, which is similar to the function defined in python and the class called in the function

  • Define the interface, and the interface calls the method
  • Initialize structure, initialize interface
  • Structure variable assignment to interface
  • Interface calls methods, and calls corresponding methods according to different structure interfaces

Continue to add the following contents to [golang code 1]:

//Define interface Namer and call method Printme
type Namer interface{
    Printme()
}

//Define structure Animal
type Animal struct{
    animals string
    sex string
}

//Define the method Printme, and the incoming recipient type is the Animal pointer type
func(a *Animal) Printme(){
    fmt.Printf("Anilmal is: %s, sex is:%s",a.animals,a.sex)
}

//Another shorthand for initializing structures
a:=&Animal{"cat","sex"}

//Initialize variable aa with interface Namer and assign a value
var aa Namer=a
//Initialize the variable pp with the interface Namer and assign the value p
var pp Namer=p

//Call the corresponding method according to the incoming recipient
aa.Printme()
pp.Printme()

In addition, the interface can be defined as a slice type, and the initialized structure is assigned to the slice, as follows:

//The initialization slice definition type is interface
who:=[]Namer{p,a}
for k,_:=range(who){
    who[k].Printme()
}

Summary:

python: defines a function whose formal parameters are classes. After instantiating the corresponding class, the function calls the corresponding class method
golang: defines an interface in which methods are defined. After initializing the corresponding structure, the variable is passed to the interface, and the interface calls the corresponding method.

Keywords: Python Go

Added by Cypher87 on Sat, 18 Dec 2021 08:55:53 +0200