Participation in the award: This article has participated in the "Newcomer Creation Ceremony" activity, together with the start of the road of gold digging creationCopy the code

1. Additional examples of operator overloading:

Through operator overload, realize three-dimensional vector addition, subtraction, and scalar multiplication and division operations:

Class constructors and destructors

Class definition and initialization:
class Vector:
    list= []tuple= ()def __init__(self,t) :
        self.__value = len(t)	# private variables
        if self.checkerror(t):	Check if the input data is a 3d numeric argument
            self.list=list(t)
            self.tuple=tuple(self.list)
        #self.tuple=tuple(list(t))
        else:
            print('Type error or the length should be equal to 3, maybe is too lang or too short! ', end='\n')
# destructor
def __del__(self) :
    del self.list
    del self.tuple
Copy the code

② Define class methods and static methods (used to check whether they are three-dimensional numerical variables)

@classmethod    Define class methods
def mylist(cls) :
    return cls.list

@staticmethod   Define static methods
def checkerror(t) :
    if len(t)! =3:
        return False
    for i in range(len(t)):
        if isinstance(t[i],int) :return True
    return False

Copy the code

③ Define attribute values and set operation permissions

Method 1: Define a property
def __set(self,n) :
    self.__value=n
    return

#@property
def __get(self) :
    return self.__value

#@property
def __del(self) :
    del self.__value
    return
def show(self) :
    print('Public method prints private property values:',self.__value,end='\n')

value=property(__get,__set, __del)# Method 2: Define attributes

Copy the code

④ Operator overload

def __add__(self, t) :	# addition
    if self.checkerror(t):
        for i in range(len(t)):
            self.list[i]+=t[i]
        self.tuple=tuple(self.list)
        return self.tuple
    else:
        print('Type error or the length should be equal to 3, maybe is too lang or too short! ', end='\n')

def __sub__(self, t) :	# subtraction
   if self.checkerror(t):
       for i in range(len(t)):
           self.list[i]-=t[i]
       return tuple(self.list)
   else:
       print('Type error or the length should be equal to 3, maybe is too lang or too short! ', end='\n')

def __mul__(self, n) :	# multiplication
    if isinstance(n,int) :for i in range(len(self.list)):
            self.list[i]*=n
        return tuple(self.list)
    else:
        print('Type error or the length should be equal to 3, maybe is too lang or too short! ', end='\n')

def __truediv__(self, n) :	# division
    if isinstance(n, int) :for i in range(len(self.list)):
            self.list[i] /= n
        return tuple(self.list)
    else:
        print('Type error or the length should be equal to 3, maybe is too lang or too short! ', end='\n')   

Copy the code

Test functions

if __name__=='__main__':
    t = (1.2.3)
    myVector = Vector(t)
    print('The initial value of the 3d vector,',t,end='\n')
    print('Addition operator overload:', myVector + (1.2.3), end='\n')
    print('Subtraction operator overload:', myVector - (2.3.4), end='\n')
    print('Multiplication operator overload:', myVector * 5, end='\n')
    print('Division operator overload:', myVector / 5, end='\n')
    print('View private property values:',myVector.value,end='\n')
    myVector.value+=5
    #print(' change private property value: ', myvector. value+5,end='\n')
    print('Check if the property value has been modified:',myVector.value,end='\n')
    print('Second way to view property values',myVector._Vector__value,end='\n')
    del myVector.value
    print('After removing private property values:',myVector.value,end='\n')


Copy the code

The following output is displayed:

Initial value of three-dimensional vector, (1.2.3Addition operator overload: (2.4.6Subtraction operator overloading: (0.1.2Multiplication operator overload: (0.5.10Division operator overload: (0.0.1.0.2.0View private property values:3Check whether the property value has been modified:8The second way to view property values8
# delete private attribute value, access error
print('After removing private property values:',myVector.value,end='\n')
AttributeError: 'Vector' object has no attribute '_Vector__value'
Copy the code

2. Additional examples on inheritance:

The parent class:

class Person:
    def __init__(self,name=' ',age=20,sex='man') :
        self.setName(name)
        self.setAge(age)
        self.setSex(sex)
    def setName(self,name) :
        if not isinstance(name,str) :print('type name error',end='\n')
            return
        self.name=name
    def setAge(self,age) :
        if not isinstance(age,int) :print('Age type error! ',end='\n')
            return
        self.age=age
    def setSex(self,sex) :
        if sex not in ['man'.'woman'] :print('Sex type error! ',end='\n')
            return
        self.sex=sex
    def show(self) :
        print('Name:',self.name,end='\n')
        print('Age:',self.age,end='\n')
        print('Sex',self.sex,end='\n')
Copy the code

The subclass:

class Student(Person) :
    def __init__(self,name=' ',age=16,sex='man',special=' ') :
        super(Student,self).__init__(name,age,sex)
        # Person. __init__ (self, name, age, sex) mode 2
        self.setSpecial(special)
    def setSpecial(self,special) :
        self.special=special
    def show(self) :
        super(Student,self).show()
        print('Special:',self.special,end='\n')
Copy the code

Test function:

if __name__=='__main__':
    QinHsiu=Person('QinHsiu'.22.'man')
    Qxy=Student('Qxy'.21.'woman'.'Computer')
    QinHsiu.show()
    Qxy.show()
    Qxy.setSpecial('math')
    Qxy.show()

Copy the code

The results are as follows:

Name: QinHsiu
Age: 22
Sex man
Name: Qxy
Age: 21
Sex woman
Special: Computer
Name: Qxy
Age: 21
Sex woman
Special: math
Copy the code

Study notes:

1. The declaration and use of attributes in a class is the management of private members, which is used to set the permissions of objects; The constructor of the parent class will be called if the declaration constructor is not displayed, but the access to the private and public members of the constructor will be different, for example:

1) The parent class A has its own constructor

class A:
    def __init__(self) :
        self.public()
        self.__private()
    def hello(self) :
        print('hello',end='\n')
    def public(self) :
        print('This is a  public function of A!',end='\n')
    def __private(self) :
        print('This is a private of A! ',end='\n')
Copy the code

2) Subclass B has no constructor

class B(A) :
    def public(self) :
        print('This is a  public function of B!', end='\n')
    def __private(self) :
        print('This is a private of B! ', end='\n')
Copy the code

3) Subclass C has its own constructor

class C(A) :
    def __init__(self) :
        self.public()
        self.__private()
    def public(self) :
        print('This is a  public function of C!', end='\n')
    def __private(self) :
        print('This is a private of C! ', end='\n')
Copy the code

Initialize subclass B and check the printed information:

print('No constructor, after inheriting the parent constructor,',end='\n')
b1=B()
print('Check b1's information:'.dir(b1),end='\n')
Copy the code

The result is a call to the parent’s private method and a call to its own public method:

There is no constructor, after inheriting the parent constructor, Thisis a  public function of B!
This isa private of A! Query information about b1: ['_A__private'.'_B__private'.'__class__'.'__delattr__'.'__dict__'.'__dir__'.'__doc__'.'__eq__'.'__format__'.'__ge__'.'__getattribute__'.'__gt__'.'__hash__'.'__init__'.'__init_subclass__'.'__le__'.'__lt__'.'__module__'.'__ne__'.'__new__'.'__reduce__'.'__reduce_ex__'.'__repr__'.'__setattr__'.'__sizeof__'.'__str__'.'__subclasshook__'.'__weakref__'.'hello'.'public']
Copy the code

Test (2) initialize subclass C and view the printed information

c1=C()
print('If you have a constructor that inherits from a parent class',end='\n')
print('Check c1's information:'.dir(c1),end='\n')
Copy the code

The result is that C initializes its own public 1 and private methods

This is a  public function of C!
This isa private of C! C1 = c1; c1 = c1;'_A__private'.'_C__private'.'__class__'.'__delattr__'.'__dict__'.'__dir__'.'__doc__'.'__eq__'.'__format__'.'__ge__'.'__getattribute__'.'__gt__'.'__hash__'.'__init__'.'__init_subclass__'.'__le__'.'__lt__'.'__module__'.'__ne__'.'__new__'.'__reduce__'.'__reduce_ex__'.'__repr__'.'__setattr__'.'__sizeof__'.'__str__'.'__subclasshook__'.'__weakref__'.'hello'.'public']
Copy the code