gpt4 book ai didi

python - 为什么断言在抽象类中不起作用?

转载 作者:太空宇宙 更新时间:2023-11-04 11:06:29 26 4
gpt4 key购买 nike

我需要你的帮助来理解为什么 assert 在我的代码中不起作用(我正在使用这段代码来学习抽象类、getter 和 setter),我是抽象类的新手。

如果我在 power 属性中放置一个负数,代码应该停止并发出警告,但如果 power 为负数、零或非负数,断言将忽略。

另一个测试代码在基类中没有具体方法,但在子类中有相同的具体方法代码停止并给我一个警告。

这是我要测试的完整代码。

from abc import ABC, abstractmethod

class Load(ABC):
#That's a class to create load to circuits.
@abstractmethod
def __init__(self, power=0, power_factor=1):
self.__power = power
self.__power_factor = power_factor

# the attributte name and the method name must be same
# which is used to set the value for the attributte
@property
def power(self):
return self.__power

@power.setter
def power(self, power):
# AT TEST SHOULD STOP HERE ANY CONDITION - ONLY TEST PURPOSEs
# BUT HERE ASSERT IS IGNORED
assert (power < 0), "power must be non-negative"
assert (power >= 0), "***power must be negative - ONLY TEST"
self.__power = power

@property
def power_factor(self):
return self.__power_factor

@power_factor.setter
def power_factor(self, power_factor):
assert 0 < power_factor <= 1, "power factor must be greater 0 until 1"
self.__power_factor = power_factor


class Specific(Load):
def __init__(self, power, power_factor):
super().__init__(power, power_factor)
# the attributte name and the method name must be same
# which is used to set the value for the attributte

### ONLY TESTs PURPOSE

a = Specific(-11,1) # TO FORCE THE ERROR
print(a.power, a.power_factor)
a.power_factor = .4
print(a.power, a.power_factor)

我做错了什么?

最佳答案

您没有使用您的 setter - 您直接分配给您的支持字段。

使用

class Load(ABC):
#That's a class to create load to circuits.
@abstractmethod
def __init__(self, power=0, power_factor=1):
self.power = power # acutally use the setter, do not
self.power_factor = power_factor # set the backing field directly...

因此您的设置人员会检查这些值。

关于python - 为什么断言在抽象类中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59324660/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com