showkey
showkey

Reputation: 298

How to check the class attribution dynamically?

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)

The code will be executed 9 times. Every time, a window with how height are you pops up, and you can input a value.

Now what I want is for self.height to be fixed the first time I enter a value and for there to be no more how height are you pop-ups from the second time (that is to say i=1) onwards.

class  test():
    def __init__(self):
        if (  self.height has no value):  
            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)

How to fill it with some code or change it into other structure?

Upvotes: 0

Views: 156

Answers (4)

Patrick the Cat
Patrick the Cat

Reputation: 2158

You can create a Factory class to produce the Test instances dynamically, like the following:

class Test(object):

    def __init__(self, height):
        self.height = height

    def fun(self, x):
        print(x + self.height)

class TestFactory(object):

    def __init__(self):
        self.height = None

    def test(self):
        if self.height is None:
            self.height = int(input("how height are you"))
        return Test(self.height)

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

In this case Test is a normal class of static initialization, but you assign initial parameter dynamically. This is quite a common practice in Java.

Upvotes: 0

Avinash Babu
Avinash Babu

Reputation: 6252

This can be done by creating and object of the function and passing it through the loop.

class  test():
def __init__(self):
    self.height=int(input("How tall are you? "))
def fun(self,x):
    print(x+self.height)
Theobject = test()
for m in range(1,10):
obj.fun(i)

Upvotes: 0

Mike Bell
Mike Bell

Reputation: 1396

You are instantiating test() every iteration of the loop, which runs the __init__ function (and resets instance members).

I think what you want to do is instantiate test outside the loop:

testObject = test()

and use the object in the loop:

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

Upvotes: 1

jwodder
jwodder

Reputation: 57590

Only create a single test object once (before the for loop) and you'll only have to input a value once:

class  test():
    def __init__(self):
        self.height=int(input("How tall are you? "))
    def fun(self,x):
        print(x+self.height)

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

(I also took the liberty of correcting the input prompt.)

Upvotes: 0

Related Questions