python这道题啥意思?怎么做?

Python017

python这道题啥意思?怎么做?,第1张

python这道题是面向对象的用法考查,以复数类的构建为例,结合一点复数知识填入而可,排版和代码如图,注意填入的缩进(选中的代码是题目内容,没选中的是测试代码,效果如下)

class Comp():

def __init__(self,re=1,im=0):

self.__re=re

self.__im=im

def __str__(self):

return (

"%f+%fi"%(self.__re,self.__im))

def __lt__ (self, other):

print("复数不能比大小")raise

def __ge__ (self, other):

print("复数不能比大小")raise

def __le__(self, other):

print("复数不能比大小")raise

def __eq__ (self, other):

print("复数不能比大小")raise

def __ne__ (self, other):

print("复数不能比大小")raise

def __add__ (self,other):

return Comp(re=self.__re

+other.__re,im=self.__im

+other.__im)

def __sub__ (self, other):

return Comp(re=self.__re

-other.__re,im=self.__im

-other.__im)

第二种相当于是局部变量,除了init函数外,其他的地方都不能访问

第三种相当于是类的属性,每个具体的对象有不同的值,在其他类中如果生成了对象b,如b=a(),使用b.aa可以访问到。

第一种是定义了类的变量,所有的对象共享该变量,在其他类中使用a.aa可以访问到,注意这里a是类的名字,也可以通过每个对象访问到,如b=a() c=a() ,则b.aa与c.aa及a.aa都是访问的一个东西,值是一样的。