Comparison between java and python classes

1. constructor

Methods and variables

super,self,this

4. python code instance

class Test():
    # Class attribute
    country = 'China'
    province = 'Shaanxi Province'
    city = 'Xi'an City'
    readme = 'I am a parent class property'

    
    # Member attribute
    def __init__(self, name, age, sex, district, native, party_member):
        self.name = name  # Define or call member properties using (self. Variable name)
        self.age = age
        self.sex = sex
        Test.add_information = 'Defining class properties within the constructor'
        self.city = self.city + district  # python executes the one after the equal sign first, and the self.city after the equal sign is the calling class attribute (self.city will first find out whether there is a city in the member attribute, and then not from the class.
        # Since the right side of the equal sign is executed before the equal sign, and the member attribute has no city, the self.city on the right side of the equal sign is a class attribute.)
        # The self.city on the left side of the equal sign is a member attribute, which is equivalent to defining a member attribute self.city, and assigning it as the city in the class plus district
        # If the self. Attribute or self. Method appears on the right side of the equal sign, it will be found (called) from the member attribute or method first. If there is no member, it will be found in the class
        Test.province  = self.province + '('+ native + ')' # The left and right sides of the equal sign are class properties. This code modifies the value of class properties
        self.readme = Test.description() 
        self.laud = self.praise() 
        self.income = self.salary(party_member) # Call member method
    
    # Member method
    def salary(self, party_member):
        if party_member:
            money = 10000
        else:
            money = 11000
        return money
    
    # Member method
    def more_information(self, party_member):
        less_info = self.description() #  Member methods can call class methods
        more_info = self.country + Test.province + self.city  # Member methods can call class properties and member properties
        money = self.salary(party_member)  # Member methods can call member methods
        print(less_info)
        print(more_info) 
        print('My salary is' + str(money))
        self.test()
        
    def class_method_order():
        self.test()  # First, find it from the class method, not from the member method
        
    def test(self,):
        print('Test call order: I am a member method of the parent class')        
        
    def test_1(self, ):
        print('I am a parent member method')
     
    # Class method
    @classmethod
    def description(cls, ):
        sent = 'I come from' + Test.country + Test.province + Test.city # Class methods can call class properties or class methods without any examples
        # sent = 'I come from' + self.country + Test.province + Test.city  # Error, the class method cannot call the member property. Since self. Starts, it will find the member property first
        # So even if country is a class property, but because of the self decoration, it will first find from the member property, and the class method cannot call the member property, so an error is reported
        return sent

    # Class method
    @classmethod
    def praise(cls, ):
        sent = 'As a person' + Test.country + 'I'm very proud of people'
        return sent
    
    # Class method
    @classmethod
    def test_2(cls, ):
        print('I'm a superclass method')
               
    @classmethod
    def test(cls,):
        print('Test call order: I am the parent class method')
person = Test(name='Zhang Li', age=30, sex='female', district='Weiyang District', native='external population', party_member=True)
print(person.city) # city of instance
print(Test.city) # The city of class is different from the result of instance city
print(Test.add_information)
print(person.add_information)
print(person.country)  # First, find out whether there is a country attribute from the instance. I didn't find it. I found it from the class. So this is a class attribute. It's a bit like LEGB
print(Test.country)
person.more_information(True)
# Test.more_information(party_member=True)# Error, class name cannot be followed by member property or method
print(person.description())
print(Test.description())
print(person.readme)
print(person.laud)
print(person.income)
print(person.test())
print(Test.test())
Weiyang District, Xi'an
 Xi'an City
 Defining class properties within the constructor
 Defining class properties within the constructor
 China
 China
 I come from Xi'an, Shaanxi Province, China
 Weiyang District, Xi'an City, Shaanxi Province, China
 My salary is 10000
 Test call order: I am the parent class method
 I come from Xi'an, Shaanxi Province, China
 I come from Xi'an, Shaanxi Province, China
 I come from Xi'an, Shaanxi Province, China
 I'm very proud to be a Chinese
10000
 Test call order: I am the parent class method
None
 Test call order: I am the parent class method
None
class Prac(Test): # This sentence only inherits the code other than the constructor, and the member attribute is defined in the constructor, so the member attribute has not been inherited.
    # Attributes of this class
    title = 'Test how to call properties and methods of this class and its parent class (properties of this class)'
    readme = 'I come from China (this type of attribute)'
    country = 'U.S.A'  # Override of properties
    
    def __init__(self, name, age, sex, district, native, party_member): 
        super(Prac, self).__init__(name, age, sex, district, native, party_member)# Inherit parent constructor
        # Attributes of this class
        self.direction =  'I'm a tester(Member properties of this class)'
        self.readme = 'I come from Xi'an City, Shaanxi Province, China (member attribute of this category)'
        self.age = 1000
        
    def test(self,):
        print('Test call order: I am a member method of this class')
    
    
    def test_3(self,):
        print('Methods for testing members of this class')
    
    def print_information(self,):
        
        # Self attribute: class attribute and member attribute of this class and parent class can be called through self
        print(self.direction)  # Use self to call member properties of this class
        print(self.title)  # Use self to call class properties of this class
        print('Parent member properties:', self.age)  # Using self to call the parent member property
        print('Parent class properties:', self.country)  # Using self to call parent class properties
        print("############self Attribute completed####################")
        
        # Test self call property order
        print(self.readme) # First from the member properties of this class, then from the member properties of the parent class, then from the class properties of this class, and finally from the properties of the parent class
        print('#####self Property call sequence complete######')
        
        # self method: this class 
        self.test_3()  # Use self to call member methods of this class
        self.test_4()  # Use self to call this class method
        self.test_1()  # Using self to call the member method of the parent class
        self.test_2()  # Using self to call the parent class method
        print("############self Method completed####################")        

        # Test self call method order
        print(self.test()) # First from the methods of this class, then from the member methods of this class, then from the methods of the parent class, and finally from the member methods of the parent class
        # This class and the parent class have the same class method or member method at the same time, which is actually the rewriting of the method, that is, a manifestation of polymorphism
        print('#####self Method call sequence test completed######')
        
        # super property & method (only used to call the parent class)
        # print(super().age)  # Error: cannot call parent member property with super
        print(super().country) # You can use super to call class properties
        super().test_1()  # Member methods can be called using super
        super().test_2()  # You can use super to call class methods
        super().test() # If the parent class and member have the same method, call the parent class method first, and no member method is found
        print("###############super Complete#############")
        
        # Parent class.
        # print(Test.age)  # Cannot use parent class. Member property
        print(Test.country)  # You can use the parent class. Class property
        # Test.test_1()  # Cannot use parent class. Member method
        Test.test_2()  # You can use the parent class. Class method      
        
    @classmethod
    def test_4(cls,):
        print('Test this kind of method')

    @classmethod
    def test(cls,):
        print('Test call order: I am the class method of this class')
ex = Prac(name='Zhang Li', age=30, sex='female', district='Weiyang District', native='external population', party_member=True)
ex.print_information()
print(ex.country)
I am a tester (member property of this class)
Test how to call properties and methods of this class and its parent class (properties of this class)
Parent member property: 1000
 Parent class attribute: US
 ############End of self attribute####################
I come from Xi'an City, Shaanxi Province, China (member attribute of this category)
#####End of self property call sequence######
Methods for testing members of this class
 Test this kind of method
 I am a member method of the parent class
 I'm a superclass method
 ############End of self method####################
Test call order: I am the class method of this class
None
 #####self method call sequence test completed######
China
 I am a member method of the parent class
 I'm a superclass method
 Test call order: I am the parent class method
 ###############super over#############
China
 I'm a superclass method
 U.S.A

5. java code instance

package practice01;

public class test1 {
    // Premise note: because all variables in java need to be declared in advance, and the same scope variables cannot be declared repeatedly, it is impossible for class properties and member properties to have the same name (different from python)
    // And all class attributes and member attributes need to be defined in (a tab different from public class).
    // Class method and member method are the same: class method and member method cannot have the same name

    // Whether the parent class or the child class is a class or a member, whether the property or the method, the name is the same, that is, rewriting, is a manifestation of polymorphism.


    // Class attribute
    public static String country = "China";
    public static String province = "Shaanxi Province";
    public static String city = "Xi'an City";
    public static String readme;

    // Member attribute
    public String name;
    public int age;
    public String sex;
    public int income;
    public String sentence;
    public String laud;

    public test1(String name_, int age, String sex, String district, String native_, boolean party_member){
        name = name_;  // When the name of parameter and member property is different, the member property is assigned directly
        this.age = age;  // When the name of parameter and member property is different, this must be added before the member property assignment
        this.sex = sex;
        this.readme = "I am a class property"; // Assign a value to the class attribute in the constructor, use the class. Call the class attribute
        this.sentence = this.description();  // Use this to call class methods
        this.laud = test1.praise();  // Use class. Method to call class method
        this.income = salary(party_member);  // Call member methods directly
    }

    // Member method
    public int salary(boolean party_member){
        int money;
        if (party_member){
            money = 10000;
        }
        else{
            money = 11000;
        }
        return money;
    }

    public void test(){
        System.out.println("Test it.");
    }

    // Class method
    public static String description(){
        String sent = "I come from" + country + province + test1.city; // this.country cannot be used. Similar to python, static methods cannot use non-static variables
        return sent;
    }

    public static String praise(){
        String sent = "As a person" + country + "I'm very proud of people";
        return sent;
    }

    public static void main(String[] args){
        test1 ex = new test1("Lucy", 15, "female", "Weiyang District", "external population", true);
        System.out.println(ex.name);
        System.out.println(ex.age);
        System.out.println(ex.readme);
        System.out.println(ex.sentence);

    }
}
Lucy
15
 I am a class property
 I come from Xi'an, Shaanxi Province, China
package practice01;

public class test2 extends test1 {

    public test2(String name_, int age, String sex, String district, String native_, boolean party_member, int rank){
        super(name_, age, sex, district, native_, party_member);   //Constructor inheritance
        this.rank = rank;
        this.age = 10000;
    }

    public int rank;
    public int age;

    // Class property override
    public static String country = "U.S.A";
    public static String sex = "Unclear";


    // Class method rewriting
    public static String description(){
        String sent = "I'm a subclass method";
        return sent;
    }

    // Member method override
    public void test(){
        System.out.println("Test it again");
    }

    // Calling parent class
    public void print_(){
        System.out.println(this.income); // Call parent member properties
        System.out.println(this.age); // Both the parent class and the child class have age s. First, look from the child class
        System.out.println(super.age); // Call parent member properties
        System.out.println(test1.country); // Call parent class properties
        System.out.println(this.city); // Call parent class properties
        System.out.println(super.province); // Call parent class properties
        System.out.println(this.sex);
        this.test();  // Both the parent class and the child class have member methods. First, look from the child class
        super.test(); // super specifies to find from the parent class. Although method rewriting is used here, the parent class can still be called. Polymorphism
    }

    public static void main(String[] args){
        test2 ex = new test2("Lucy", 15, "female", "Weiyang District", "external population", true, 1);
        ex.print_();
    }

}
10000
10000
15
 China
 Xi'an City
 Shaanxi Province
 Unclear
 Test it again
 Test it.
123 original articles published, 128 praised, 20000 visitors+
Private letter follow

Tags: Attribute Python Java

Posted on Mon, 16 Mar 2020 19:28:41 -0700 by ghostrider1