如何对属性进行操作
classtest():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从此固定下来,以后每次实例初始化的时候,不再执行赋值,请问如何完成?
classtest():
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) classtest():
def __init__(self):
self.height=int(input("how height are you:"))
def fun(self, x):
print(x + self.height)
t = test()
for i in range(1,10):
t.fun(i) 能否在test类里面加个对属性的判断来实现? 回复 3# luofeiyu_cu
什么意思? 回复 4# ssfjhh
估计楼主是需要一个类似于通常面向对象语言的static property的例子。 回复 1# luofeiyu_cu
因为Python里面,类似面向对象的static property是在类的空间,不是实例化对象的空间的,所以使用时的方法应当类似下面的方式,而不是使用self访问:
(在你原来的代码中修改了下。)classtest():
Height = 0
def __init__(self):
if (test.Height == 0):
test.Height=int(input("how height are you"))
def fun(self,x):
print(x + test.Height)
for i in range(1,10):
test().fun(i)
页:
[1]