鱼C论坛

 找回密码
 立即注册
查看: 790|回复: 3

关于类的一个问题

[复制链接]
发表于 2019-3-10 22:20:39 | 显示全部楼层 |阅读模式

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

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

x
class Fish:
    def number(self,x):
         self.x = x
         print(colour(self.x))

    def colour(y):
        if y == 1:
            return yellow
        else:
            return green

+++++++++++++++++++++++++++
运行程序:
f = Fish()
f.number(1)


Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    f.number(1)
  File "C:\Users\Administrator\Desktop\新建文本文档.py", line 4, in number
    print(colour(self.x))
NameError: name 'colour' is not defined
+++++++++++
问题1:
我就是想在类里面调用 colour()这个函数 为什么不能调用
问题2:
怎么样实现在类里面调用函数的功能
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2019-3-10 22:29:13 | 显示全部楼层
本帖最后由 幽梦三影 于 2019-3-10 22:56 编辑

print(self.colour(self.x))
def colour(self, y):
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-3-10 22:38:51 | 显示全部楼层
一种方法是color()作为类的一个方法进行调用。代码如下
  1. class Fish:
  2.     def number(self,x):
  3.          self.x = x
  4.          print(self.colour(self.x))   #self.colour调用自身的colour方法。

  5.     def colour(self,y):   #方法括号内需加入self)
  6.         if y == 1:
  7.             return 'yellow'   #返回需要字符串。
  8.         else:
  9.             return 'green'
复制代码



另一种方法就是colour作为一个独立函数,代码如下
  1. class Fish:
  2.     def number(self,x):
  3.          self.x = x
  4.          print(colour(self.x))

  5. def colour(y):
  6.     if y == 1:
  7.         return 'yellow'
  8.     else:
  9.         return 'green'
复制代码


你出错最主要是clour函数缩进错误。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-3-10 22:43:44 | 显示全部楼层
字符串要引号
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2026-1-14 12:14

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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