Python程序设计之面向对象程序设计(3)

1.关于运算符重载的补充实例:

通过运算符重载,实现三维向量的加法,减法,和标量的乘法和除法运算:

①类的构造函数和析构函数

#类定义及初始化:
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

②定义类方法和静态方法(用于检查是否为三维数字变量)

@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

③定义属性值,可以设置操作权限

#@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)#方式二定义属性

④运算符重载

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

测试函数

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

输出结果如下:

三维向量初始值, (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.关于继承的补充实例:

父类:

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

子类:

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

测试函数:

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

结果如下:

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

学习笔记:

1.类中属性的声明和使用是对私有成员的管理,用来设置对象对其的权限;
2.继承中子类初始化时,如果没有显示声明构造函数,会调用父类的构造函数,但是对于构造函数中的私有成员和公有成员的访问会不同,例如:

1)父类A有自己的构造函数

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)子类B没有构造函数

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)子类C有自己的构造函数

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

测试①初始化子类B,并查看打印信息:

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

结果如下,初始化时调用父类的私有方法,调用自己的公有方法:

没有构造函数,继承父类构造函数后,
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']

测试②初始化子类C,并查看打印信息

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

结果如下,初始化子类C调用自己的公有1和私有方法

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']

面向对象程序设计基础(1):

https://blog.csdn.net/qxyloveyy/article/details/104554448

面向对象程序设计基础(2):

https://blog.csdn.net/qxyloveyy/article/details/104563445

发布了78 篇原创文章 · 获赞 83 · 访问量 5412

猜你喜欢

转载自blog.csdn.net/qxyloveyy/article/details/104579742