mercredi 24 juin 2020

Creating instance of a class with random arguments in another class in python

How can an instance of a class that requires an argument be created in another class, with the argument generated randomly?

In the code below I have a 'Square' class that takes a 'height' argument. I then create a 'Cube', based on the 'Square'. The problem is with the 'add_cube' method inside the 'CubeTower' class, where I cannot figure out if I need to provide a 'cube' and 'height' or only one of these arguments. This in turn throws an error when I try to call the 'add_cube' inside a loop that creates cubes with a random side height.

(There are additional methods I have in the 'Cube' class, but they are irrelevant to this problem so I did not include them).

from random import randint

class Square:
    def __init__(self, height):
        self.height = height
    
class Cube:
    def __init__(self, height):
        self.base = Square(height)
                
class CubeTower:
    def __init__(self):
        self.tower = []
        
    def add_cube(self, cube, height): # This is where I think I am doing something wrong
        cube = Cube(height)
        if not self.tower:
            self.tower.append(cube)
        else:
            if cube.base.height < self.tower[-1].base.height:
                self.tower.append(cube)
    
    def randomize_tower(self):
        for c in range(2, 100):
            height = randint(1, 100)
            c = Cube(height)
            self.add_cube(c, height)



Aucun commentaire:

Enregistrer un commentaire