目录
阅读下面的代码,给出输出结果。
(1)?
class A:
def __init__(self,a,b,c):self.x=a+b+c
a= A(3,5,7);b = getattr(a,'x');setattr(a,'x',b+3);print(a.x)
?
18
(2)
class Person:
def __init__(self, id):self.id = id
?
wang = Person(357); wang.__dict__['age'] = 26
wang.__dict__['major'] = 'computer';print (wang.age + len(wang.__dict__))
?
print(wang.__dict__)
print (wang.age + len(wang.__dict__))
print (wang.__dict__['age'] + len(wang.__dict__)){'id': 357, 'age': 26, 'major': 'computer'}
29
29
(3)
class A:
def __init__(self,x,y,z):
self.w = x + y + z
?
a = A(3,5,7); b = getattr(a,'w'); setattr(a,'w',b + 1); print(a.w)
?16
(4)
class Index:
? def __getitem__(self,index):
? return index
x = Index()
for i in range(8):
print(x[i],end = '*')
0*1*2*3*4*5*6*7*
(5)
class Index:
data = [1,3,5,7,9]
def __getitem__(self,index):
print('getitem:',index)
return self.data[index]
x = Index(); x[0]; x[2]; x[3]; x[-1]
getitem: 0
getitem: 2
getitem: 3
getitem: -1
(6)
class Squares:
def __init__(self,start,stop):
self.value = start - 1
self.stop = stop
def __iter__(self):
return self
def __next__(self):
if self.value == self.stop:
raise StopIteration
self.value += 1
return self.value ** 2
?
for i in Squares(1,6):
print(i,end = '<')
1<4<9<16<25<36<
(7)
class Prod:
def __init__(self, value):
self.value = value
def __call__(self, other):
return self.value * other
p = Prod(2); print (p(1) ); print (p(2))
2
4
(8)
class Life:
def __init__(self, name='name'):
print('Hello', name )
self.name = name
def __del__(self):
print ('Goodby', self.name)
brain = Life('Brain');brain = 'loretta'
?Hello Brain
Goodby Brain
(1)编写一个类,用于实现如下功能。
① 将十进制数转换为二进制数。
② 进行二进制的四则计算。
③ 对于带小数点的数用科学计数法表示。
class BinaryCalculator:
def __init__(self):
self.converter = 2
def decimal_to_binary(self, decimal):
binary = bin(decimal)
return binary[2:] # 去掉前缀 '0b'
def binary_calculator(self, binary_str):
# 加法
addition = self.calculate('add', binary_str)
# 减法
subtraction = self.calculate('subtract', binary_str)
# 乘法
multiplication = self.calculate('multiply', binary_str)
# 除法
division = self.calculate('divide', binary_str)
return addition, subtraction, multiplication, division
def calculate(self, operation, binary_str):
# 分离操作数和操作符
operator = eval(operation)
num1, num2 = map(int, binary_str.split(self.converter))
result = operator(num1, num2)
return str(result).zfill(len(binary_str)) # 用0填充到和原始二进制字符串一样长
def scientific_notation(self, decimal):
scientific = f"{decimal:.6e}" # 用6位小数表示科学计数法
return scientific
(2)编写一个三维向量类,实现下列功能。
① 向量的加、减计算。
② 向量和标量的乘、除计算。