【发布时间】:2022-08-14 21:17:45
【问题描述】:
class Item:
pay_rate = 0.8 # The pay after %20 discount
all = []
def __init__(self, name: str, price: float, quantity=0):
#Run validations to the recieved arguments
assert price >= 0, f\"Price {price} is not greater than or equal tozero!\"
assert quantity >= 0, f\"Quantity {quantity} is not greater than or equal to zero!\"
# Assign to self object
self.name = name
self.price = price
self.quantity = quantity
#Actions to execute
Item.all.append(self)
def calculate_total_price(self):
return self.price * self.quantity
def apply_discount(self):
self.price = self.price * self.pay_rate
@classmethod
def instantiate_from_csv(cls):
with open(\'items.csv\', \'r\') as f:
reader = csv.DictReader(f)
items = list(reader)
for item in items:
Item(
name=item.get(\'name\'),
price=float(item.get(\'price\')),
quantity=int(item.get(\'quantity\')),
)
@staticmethod
def is_integer(num):
#We will count out the floats that are .0
if isinstance(num, float):
#Count out the floats that are point zero
return num.is_integer()
elif isinstance(num, int):
return True
else:
return False
def __repr__(self):
return f\"Item(\'{self.name}\', {self.price}, {self.quantity})\"
我目前正在学习 python 并试图理解 OOP 概念。除了以下几行之外,我都理解了
def is_integer(num):
#We will count out the floats that are .0
if isinstance(num, float):
#Count out the floats that are point zero
return num.is_integer()
elif isinstance(num, int):
return True
else:
return False
有人能解释一下为什么 num.is_integer() 返回 False 吗? 该函数的定义是为了从像 100.0 或 50.0 这样的浮点数中删除 .0 (教程说)
第一次遇到这种return用法。习惯了return a*b或者return \'Hi\'之类的东西。
-
该方法用于检查某物是否为整数......就是这样,如果它被认为是整数,则返回
True,否则返回False,也不需要else:,可以取消缩进return False并删除else: -
只是一个意见问题,但我认为 is_integer() 函数用词不当。例如:(1.0).is_integer() == 真但它根本不是整数。这是一个没有重要小数位的浮点数
标签: python python-3.x function oop