from decimal import Decimal
from abc import ABCMeta, abstractmethod
class List(type):
pass
class Progressionmeta(type):
def __call__(cls, *args, **kwargs):
if len(kwargs) != 2:
error = "SyntaxError"
raise SyntaxError
else:
if "step" not in kwargs:
error = "KeyError"
raise KeyError
else:
if len(kwargs[0]) != 3:
error = "SyntaxError"
raise SyntaxError
return type.__call__(cls, *args, **kwargs)
class Progression(Progressionmeta, metaclass = ABCMeta):
@abstractmethod
def __init__(self):
pass
def __getitem__(self):
pass
def __iter__(self):
pass
def __next__(self):
pass
def __call__(self, *args, **kwargs):
pass
class Arithmetic_progression(metaclass = Progression):
def __init__(self, step, start=1):
self.__start = Decimal(f"{start}")
self.__step = list(step)
_ = []
for i in self.__step:
i = Decimal(f"{i}")
_.append(i)
self.__step = _
self.__x = Decimal("1")
def __getitem__(self, index):
return float(self.__start + Decimal((index * (index + 1) * (2 * index + 1) - 6) / 6) * self.__step[2] +
Decimal(((index * (index + 1) - 2) / 2)) * self.__step[1] +
Decimal(index - 1) * self.__step[0])
def __iter__(self):
return self
def __next__(self):
if self.x == Decimal("1"):
self.__a = self.__start
self.__x += Decimal("1")
return float(self.a)
else:
self.__a = self.a + (self.__step[2] * self.__x * self.__x) + (self.__step[1] * self.__x) + self.__step[0]
self.__x += Decimal("1")
return float(self.__a)
def __call__(self, start, stop):
sum_ = Decimal("0")
for i in self:
sum_ += i
return sum_
Traceback (most recent call last):
File "C:\Users\aston\AppData\Local\Programs\Python\Python311\Python\Python学习\类\list.py", line 39, in <module>
class Arithmetic_progression(metaclass = Progression):
TypeError: Progression.__init__() takes 1 positional argument but 4 were given
这个错误是因为你在声明 Arithmetic_progression 时使用了错误的 metaclass 参数。你应该使用 Progression 作为元类,而不是将 Progression 设置为 Arithmetic_progression 的 metaclass 。下面是正确的声明:
class Arithmetic_progression(Progression):
...
另外,在 __getitem__() 方法中, kwargs[0] 会引发一个 TypeError ,因为 kwargs 是一个字典,你应该使用 kwargs['step'] 来访问 step 参数。修改后的 ProgressionMeta 类应该如下:
class ProgressionMeta(type):
def __call__(cls, *args, **kwargs):
if len(kwargs) != 2:
error = "SyntaxError"
raise SyntaxError
else:
if "step" not in kwargs:
error = "KeyError"
raise KeyError
else:
if len(kwargs['step']) != 3:
error = "SyntaxError"
raise SyntaxError
return type.__call__(cls, *args, **kwargs)
|