鱼C论坛

 找回密码
 立即注册
查看: 3830|回复: 4

[已解决]python中__init__函数提问(菜鸟提问)

[复制链接]
发表于 2017-7-17 14:27:52 | 显示全部楼层 |阅读模式

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

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

x
在Pyhton中,创建一个类,同时创建他的构造函数(__init__),在构造函数下创建实例对象,为什么要加self.
例如:

Class Bird():
        def __init__(self):
        self.name='小鸟'


Class Bird():
        def __init__(self):
        name='小鸟'


上面两个代码有什么区别?
最佳答案
2017-7-17 15:32:41
本帖最后由 gopythoner 于 2017-7-17 15:34 编辑

看看效果,再看疗效
  1. class Bird():
  2.   def __init__(self):
  3.     self.name='小鸟'
  4.     year = 100
  5.    
  6.   def test(self):
  7.     print(self.name)  #这里可以直接使用,self.name
  8.     print(year)       #这里就不能使用,强行打印会报错

  9. b = Bird()
  10. b.test()
复制代码


看输出,是不是下面那个打印报错了
  1. 小鸟
  2. Traceback (most recent call last):
  3.   File "python", line 11, in <module>
  4.   File "python", line 8, in test
  5. NameError: name 'year' is not defined
复制代码


通俗来讲,加了self的属性就是可以直接传递下去,让类的其他函数都能直接引用
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2017-7-17 14:51:44 | 显示全部楼层
底下是错误的写法,类的私有属性必须加self关键字
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-7-17 14:52:06 | 显示全部楼层
实例化一个Bird对象我bird = Bird()
第二个无法通过bird.name 来访问name属性
要访问需要在类内部调用super().name
也就是说,不带self的属性属于最原始的父类,可以说不会被子类继承,但是子类仍然可以访问父类属性
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-7-17 15:12:22 | 显示全部楼层
一个是实例对象的属性,一个是类对象的属性,OK ?
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-7-17 15:32:41 | 显示全部楼层    本楼为最佳答案   
本帖最后由 gopythoner 于 2017-7-17 15:34 编辑

看看效果,再看疗效
  1. class Bird():
  2.   def __init__(self):
  3.     self.name='小鸟'
  4.     year = 100
  5.    
  6.   def test(self):
  7.     print(self.name)  #这里可以直接使用,self.name
  8.     print(year)       #这里就不能使用,强行打印会报错

  9. b = Bird()
  10. b.test()
复制代码


看输出,是不是下面那个打印报错了
  1. 小鸟
  2. Traceback (most recent call last):
  3.   File "python", line 11, in <module>
  4.   File "python", line 8, in test
  5. NameError: name 'year' is not defined
复制代码


通俗来讲,加了self的属性就是可以直接传递下去,让类的其他函数都能直接引用
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-5-18 06:43

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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