Class

Python Parser introduces the class mechanism, which currently supports basic features such as function encapsulation and operator overloading. However, it does not support advanced features such as class inheritance or defining classes inside a function.

Example 1: Function Encapsulation

class student:
    def __init__(self, name, gender, score_list):
        self.name = name
        self.gender = gender
        self.score = score_list

    def get_avgScore(self):
        return avg(self.score.toddb())
    
    def get_Info(self):
        print("name:", self.name)
        print("gender:", self.gender)
        print("avgScore:", self.get_avgScore())

x = student("pl", "male", [100, 99, 98, 92])
x.get_Info()

Output:

name: pl

gender: male

avgScore: 97.25

Example 2: Operator Overloading

The following example defines a class Complex, which uses the method __add__ to overload the "+" operator and the method __repr__ to represent objects.

class Complex:
    def __init__(self, realpart, imagpart):
        self.r = realpart
        self.i = imagpart
    def __add__(self, other):
        return Complex(self.r + other.r, self.i + other.i)
    def __repr__(self):
        sign = "+" if self.i >= 0 else ""
        return str(self.r) + sign + str(self.i) + "i"

x = Complex(3, 4)
y = Complex(0, -1)
x

Output: 3+4i

y

Output: 0-1i

z

Output: 3+3i