免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2624 | 回复: 5
打印 上一主题 下一主题

如何对属性进行操作 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2014-08-02 10:03 |只看该作者 |倒序浏览
class  test():
    def __init__(self):
        self.height=int(input("how height are you"))
    def fun(self,x):
        print(x+self.height)

for i in range(1,10):
    test().fun(i)

上面的代码会执行10次,每次都有how height are you 跳出,要求你输入值。

现在,我希望在第一次输入值后,self.height从此固定下来,以后每次实例初始化的时候,不再执行赋值,请问如何完成?

class  test():
    def __init__(self):
        if (  self.height的值不存在):  #这里如何完成?
            self.height=int(input("how height are you"))
    def fun(self,x):
        print(x+self.height)

for i in range(1,10):
    test().fun(i)

论坛徽章:
4
金牛座
日期:2013-10-11 16:12:50卯兔
日期:2014-07-31 09:17:19辰龙
日期:2014-08-08 09:28:02狮子座
日期:2014-09-14 20:32:05
2 [报告]
发表于 2014-08-02 11:44 |只看该作者
  1. class  test():
  2.     def __init__(self):
  3.         self.height=int(input("how height are you:"))
  4.     def fun(self, x):
  5.         print(x + self.height)

  6. t = test()
  7. for i in range(1,10):
  8.     t.fun(i)
复制代码

论坛徽章:
0
3 [报告]
发表于 2014-08-02 19:12 |只看该作者
能否在test类里面加个对属性的判断来实现?

论坛徽章:
4
金牛座
日期:2013-10-11 16:12:50卯兔
日期:2014-07-31 09:17:19辰龙
日期:2014-08-08 09:28:02狮子座
日期:2014-09-14 20:32:05
4 [报告]
发表于 2014-08-02 19:39 |只看该作者
回复 3# luofeiyu_cu


    什么意思?

论坛徽章:
4
白羊座
日期:2013-11-05 10:26:09冥斗士
日期:2015-11-17 14:19:55白银圣斗士
日期:2015-11-17 15:13:0815-16赛季CBA联赛之新疆
日期:2016-04-01 09:10:58
5 [报告]
发表于 2014-08-04 11:03 |只看该作者
回复 4# ssfjhh
估计楼主是需要一个类似于通常面向对象语言的static property的例子。

论坛徽章:
4
白羊座
日期:2013-11-05 10:26:09冥斗士
日期:2015-11-17 14:19:55白银圣斗士
日期:2015-11-17 15:13:0815-16赛季CBA联赛之新疆
日期:2016-04-01 09:10:58
6 [报告]
发表于 2014-08-04 11:08 |只看该作者
回复 1# luofeiyu_cu
因为Python里面,类似面向对象的static property是在类的空间,不是实例化对象的空间的,所以使用时的方法应当类似下面的方式,而不是使用self访问:
(在你原来的代码中修改了下。)
  1. class  test():
  2.     Height = 0
  3.     def __init__(self):
  4.         if (test.Height == 0):
  5.             test.Height=int(input("how height are you"))

  6.     def fun(self,x):
  7.         print(x + test.Height)

  8. for i in range(1,10):
  9.     test().fun(i)
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP