【问题标题】:Why does the num.is_integer() function returns false为什么 num.is_integer() 函数返回 false
【发布时间】: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


【解决方案1】:

如果您的 is_integer() 函数返回 False,那是因为您要么传递了一个具有重要小数部分的浮点数,要么传递了一些既不是 int 也不是浮点数的对象。

您可能会发现对该函数的更改很有用:

def is_integer(n):
    if __debug__:
        print(type(n))
    return n.is_integer() if isinstance(n, float) else isinstance(n, int)

【讨论】:

    【解决方案2】:

    首先,这种类型的回报没有什么不寻常的。要使用您的示例:

    1. return 'Hi' - 返回字符串 'Hi'
    2. return a * b - 说 a=3, b=5,它计算 a*b 并返回结果,15
    3. return num.is_integer() - 这将检查数字是否为整数并返回结果,True 或 False

      is_integer() 上的一个注释,它会说5050.0 都是整数,尽管严格来说,50 是一个int 数据类型50.0 是一个浮点数据类型在 Python 中。如果您使用这些知识浏览下面的代码,那么它似乎做了同样的事情,只是您会用Item.is_integer(50) 调用它。

      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
      

    【讨论】:

      【解决方案3】:

      我正在学习相同的教程,实际上我来这里是为了理解同样的事情。从我所查找的内容来看,由于教程中的编写方式,这里有些混乱。对于像我们这样的初学者来说,这看起来像是一个递归函数,整个事情似乎在一个循环中,而实际上它不是,并且 is_integer() 是一个预定义函数(文档链接:https://python-reference.readthedocs.io/en/latest/docs/float/is_integer.html

      在我看来,一个更好的编写方法是将你的函数定义为 check_integer 或其他东西,这样就不会有任何歧义。我是这样做的:

      @staticmethod
      def check_int(num): #this is better than using "def is_integer(num)"
          #we will count out the floats that end with .0 e.g 5.0,10.0 etc.
          if isinstance(num,float):
              #count out floats with point zero
              return num.is_integer()
          if isinstance(num,int):
              return True
          else:
              return False 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-28
        • 2018-08-27
        • 2018-11-09
        • 1970-01-01
        • 2013-09-18
        • 2019-05-20
        • 2020-10-17
        相关资源
        最近更新 更多