This is the 9th day of my participation in the August More Text Challenge. For details, see:August is more challenging

The background,

Domestic official tutorial rookie tutorial other tutorial

The Python language is more abstract than Java, more natural language, easy to learn, and the same function Python code is the least amount of code. Here’s an example:

1.1 Java example

// Define a Student class
class Student {
    // Define a name attribute
    String name;
    int age;

    // Constructor: take a parameter
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Common method: no parameters
    public void printInfo(a) {
        System.out.println("My name is" + name + "This year" + age + "Age");
    }

    // Common method: take a parameter
    public void printLike(ArrayList<String> likes) {
        for (String like : likes) {
            System.out.println("My hobbies are:+ like); }}// Normal methods: with a return value
    public String getName(a) {
        returnname; }}class Test {
    public static void main(String[] args) {
        Student stu1 = new Student("Zhang".18);
        stu1.printInfo();
        ArrayList<String> likes = new ArrayList();
        likes.add("Table tennis");
        likes.add("Basketball");
        likes.add("Football");
        stu1.printLike(likes);
        Stu1. printLike(" string "); // Compile error
       // Student stu2 = new Student(18, "3 "); // Compile error}}Copy the code

Java output:

My name is Zhang SAN. I am 17 years old. My hobby: Table tennis My hobby: basketball My hobby: footballCopy the code

1.2 the python example

# Define a Student class
class Student:
    # Define a name attribute
    name = None
    age = None

    # Constructor: takes a parameter
    def __init__(self, name, age) :
        self.name = name
        self.age = age

    # Common method: No arguments
    def printInfo(self) :
        print("My name is" + self.name, "This year" + self.age + "Age")

    # Common method: take a parameter
    def printLike(self, likes) :
        for like in likes:
            print("My hobby:", like)
    
    # Normal method: returns a value
    def getName(self) :
        return self.name
        
if __name__ == '__main__':
    stu1 = Student("Zhang"."17")
    stu1.printInfo()
    stu1.printLike(["Table tennis"."Basketball"."Football"])
    stu1.printLike("String")
    
    stu2 = Student(17."Zhang")
    stu2.printInfo()
Copy the code

Output from Python:

My name is Zhang SAN, 17 years old my hobby: ping-pong my hobby: basketball my hobby: football My hobby: Word my hobby: Fu my hobby: String my name is 17, this year Zhang is three years oldCopy the code

1.3 Comparison results

1.3.1 Java characteristics

  • There is more Java code for the same functionality
  • Java must end each piece of code with a semicolon
  • Java code is placed in{}
  • Create an objectNew class name ()It has to be addednewThe keyword
  • To define an attribute, you must first specify the specific type
  • A normal method with a return value must specify a return type

1.3.2 python features

  • Less Python code for the same function
  • The Python code is placed in:Below, and toThe indentation
  • Create an object:The name of the class ().
  • To define an attribute, declare it directly without specifying a specific type
  • Method declarations only need to be declareddefYou do not need to declare the return type even if there is a return value

1.3.3 summary

Python is concise, but at the expense of readability. For example, in Java, the age attribute prespecifies an int, and when age = “li4”, the string is assigned to age, which makes compilation difficult. But you can do this in Python, and so Python offers the flexibility that is characteristic of the language.

If a method has no return value in Java, the return type must be void. If a method has a return value, the return type must be specified. In Python, if you want to return, return xx. If you don’t want to return, return or no return. So Java code is written from the beginning to the end, and is easier to trace back to.

Introduction to Object Orientation

2.1 Class (Class)

Encapsulates the properties and methods associated with the class. Objects are instances of the class.

# Define a Student class
class Student::# attribute
    name = ""
    age = 0 
    
   # methods
    def eat(self) :
        pass
        
Copy the code

Is it possible to define cartBrand = “” attribute in Student? Yes, but this property has nothing to do with the Student class, most of the time, the properties that we define in the class are related to the class. Stu1 = Student() stu1 is a property, it’s a variable that points to the Student() object in the heap,

2.2 Method == function

2.2.1 There are four methods

 def printInfo(self) :
    print("No arguments, no return value, default return can be omitted")
    return

def getName(self) :
    print("No arguments, return value")
    return "Andy Lau"

def printName(self, name) :
    print("There are arguments, no return values, default return can be omitted")
    return

def add(self, x, y) :
    print("There are parameters and return values")
    return x + y
Copy the code

2.2.2 Return method in method

def calc() :
    def add(x, y) :
        return x + y
    return add

result = calc()
print(result) 
      
       . Add at 0x0000026F73425820>
      
print(result(3.4)) # Output: 7
Copy the code

2.3 Variable == attribute

2.3.1 class variables

class Student:: name ="" # string
    age = 0  # Numbers
    isMan = False # bool
    likes = [  ] # list
    likeEat = ( ) # tuples
    map= {}# dictionary
Copy the code

Class variables are defined in the class and outside of the method body, and can be passed by all methodsThe self. The variableFor a visit

2.3.2 Method variables are also called local variables

def print() :: name ="" # string
    age = 0  # Numbers
    isMan = False # bool
    likes = [  ] # list
    likeEat = ( ) # tuples
    map= {}# dictionary
Copy the code

Method variables are defined inside a method and can only be accessed from within the current method.

2.4 Create == Instantiate

class Student:
    pass
stu1 = Student()
Copy the code

Student() is equivalent to New Student() in Java; Stu1 is an object of the Student class. An infinite number of objects can be created for a class

2.5 inheritance

class People:
    def eat(self) :
        print("Eat")

class Sport:
    def playPP(self) :
        print("Playing table tennis")
 
 # Inherit 2 classes
class Student(People,Sport) :
    pass

if __name__ == '__main__':
    stu1 = Student()
    stu1.eat() # Output: Eat
    stu1.playPP() # Output: play table tennis
Copy the code

In Python, a class can inherit from multiple classes. People and Sport are the parent classes of Student, and Student, as a subclass of them, can call methods of the parent class.

2.6 Method Override

Only in the context of inheritance can methods be overwritten. Method override: a subclass defines a method with the same name and parameters as the superclass

from abc import ABCMeta, abstractmethod
class People:
    def eat(self) :
        print("Eat")
        
   @abstractmethod
    def sleep(self) :
        pass
 
 # inheritance People
class Student(People) :
    Override the sleep method of the superclass
    def sleep(self) :
        print(Student sleeping)
        
if __name__ == '__main__':
    stu1 = Student()
    stu1.sleep() # Output: Students sleep
Copy the code