鱼C论坛

 找回密码
 立即注册
查看: 2031|回复: 1

类和对象

[复制链接]
发表于 2020-2-19 18:29:04 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
这个其实是38讲动动手 我知道我写的不对 就当我这是随意设置了三个变量进行运算吧。
运行这个代码的时候报错 应该是说最后print里的不是数字 而是字符串 在哪个地方能把self.daypay , self.child改为数字形式呢
class playgurand():
        daypay = 100
        weekends = 120
        child = 50

        def pays(self,daypay,child):
                self.daypay = daypay
                self.child = child
        def end(self):
                print('%f' % (self.daypay * 2 + self.child))

               
>>> a = playgurand()
>>> a.pays('daypay','child')
>>> a.end()
Traceback (most recent call last):
  File "<pyshell#99>", line 1, in <module>
    a.end()
  File "<pyshell#96>", line 10, in end
    print('%f' % (self.daypay * 2 + self.child))
TypeError: must be real number, not str
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-2-19 18:30:56 | 显示全部楼层
在 end() 方法中加个判断:

  1. class playgurand:
  2.     daypay = 100
  3.     weekends = 120
  4.     child = 50

  5.     def pays(self, daypay, child):
  6.         self.daypay = daypay
  7.         self.child = child

  8.     def end(self):
  9.         if not isinstance(self.daypay, int):
  10.             self.daypay = playgurand.daypay
  11.         if not isinstance(self.child, int):
  12.             self.child = playgurand.child
  13.         print('%f' % (self.daypay * 2 + self.child))
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-1-22 16:50

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表