Python programming and the like (below)

参与拿奖:本文已参与「新人创作礼」活动,一起开启掘金创作之路
复制代码

1. Supplementary examples on operator overloading:

Addition, subtraction, and scalar multiplication and division are performed on three-dimensional vectors through operator overloading:

① class constructor and destructor

#类定义及初始化:
class Vector:
    list=[]
    tuple=()
    def __init__(self,t):
        self.__value = len(t)	#私有变量
        if self.checkerror(t):	#检查输入数据是否为三维数字实参
            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')
#析构函数            
def __del__(self):
    del self.list
    del self.tuple
复制代码

②Define class method and static method (used to check whether it is a three-dimensional digital variable)

@classmethod    #定义类方法
def mylist(cls):
    return cls.list

@staticmethod   #定义静态方法
def checkerror(t):
    if len(t)!=3:
        return False
    for i in range(len(t)):
        if isinstance(t[i],int):
            return True
    return False

复制代码

③Define attribute values, you can set operation permissions

#@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('公有方法打印私有属性值:',self.__value,end='\n')

value=property(__get,__set,__del)#方式二定义属性

复制代码

④ operator overloading

def __add__(self, t):	#加法
    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):	#减法
   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):	#乘法
    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):	#除法
    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')   

复制代码

test function

if __name__=='__main__':
    t = (1, 2, 3)
    myVector = Vector(t)
    print('三维向量初始值,',t,end='\n')
    print('加法运算符重载:', myVector + (1, 2, 3), end='\n')
    print('减法运算符重载:', myVector - (2, 3, 4), end='\n')
    print('乘法运算符重载:', myVector * 5, end='\n')
    print('除法运算符重载:', myVector / 5, end='\n')
    print('查看私有属性值:',myVector.value,end='\n')
    myVector.value+=5
    #print('修改私有属性值:',myVector.value+5,end='\n')
    print('查看属性值是否被修改:',myVector.value,end='\n')
    print('第二种查看属性值的方法',myVector._Vector__value,end='\n')
    del myVector.value
    print('删除私有属性值后:',myVector.value,end='\n')


复制代码

The output is as follows:

三维向量初始值, (1, 2, 3)
加法运算符重载: (2, 4, 6)
减法运算符重载: (0, 1, 2)
乘法运算符重载: (0, 5, 10)
除法运算符重载: (0.0, 1.0, 2.0)
查看私有属性值: 3
查看属性值是否被修改: 8
第二种查看属性值的方法 8
#删除私有属性值之后,访问报错如下
print('删除私有属性值后:',myVector.value,end='\n')
AttributeError: 'Vector' object has no attribute '_Vector__value'
复制代码

2. Supplementary examples on inheritance:

father:

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')
复制代码

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)方式二
        self.setSpecial(special)
    def setSpecial(self,special):
        self.special=special
    def show(self):
        super(Student,self).show()
        print('Special:',self.special,end='\n')
复制代码

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()

复制代码

The result is as follows:

Name: QinHsiu
Age: 22
Sex man
Name: Qxy
Age: 21
Sex woman
Special: Computer
Name: Qxy
Age: 21
Sex woman
Special: math
复制代码

Study Notes:

1. The declaration and use of attributes in the class is the management of private members, which is used to set the permissions of the object to it; 2. When the subclass is initialized in inheritance, if the declared constructor is not displayed, the constructor of the parent class will be called, but Access to private and public members in the constructor differs, 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')
复制代码

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')
复制代码

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')
复制代码

Test ① Initialize subclass B, and view the print information:

print('没有构造函数,继承父类构造函数后,',end='\n')
b1=B()
print('查看b1的信息:',dir(b1),end='\n')
复制代码

The result is as follows. When initializing, the parent class's private method is called, and its own public method is called:

没有构造函数,继承父类构造函数后,
This is a  public function of B!
This is a private of A!
查看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']
复制代码

Test ②Initialize subclass C and view the print information

c1=C()
print('自己有构造函数继承父类后',end='\n')
print('查看c1的信息:',dir(c1),end='\n')
复制代码

The result is as follows, the initialization subclass C calls its own public 1 and private methods

This is a  public function of C!
This is a private of C!
自己有构造函数继承父类后
查看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']
复制代码

Guess you like

Origin juejin.im/post/7079585902581776391