sivanes
sivanes

Reputation: 733

Creating a class with random, multiple-value attributes

I'm struggling with writing my first program. Basically, there will be two objects, which will consist of, say, 5 attributes. Each attribute is then defined by two parameters, randint(1, 6) and randint(1, 20). The program will then evaluate the relationship of each attribute of Object1 with each attribute of Object2.

I am trying to create a class that would generate these two objects, but all I can come up with is this...

from random import randint

    class Object:
        def __init__(self):
            self.Attribute1a = randint(1,6)
            self.Attribute1b = randint(1,20)
            self.Attribute2a = randint(1,6)

and so on...

Also, is there a way to assign two or more parameters to each attribute, so that I can just have AttributeX, not AttributeXa and then AttributeXb?

Upvotes: 0

Views: 423

Answers (1)

AaronB
AaronB

Reputation: 306

What you're looking for is a tuple: self.Attribute1 = (randint(w,x), randint(y,z)) where w, x, y, and z are whatever constants you want. Then, you can compare them by accessing each column individually: Attribute1[0] and Attribute1[1].

Here's an idea: let's try to take your first program concept and make it a little more object-oriented. While the program you describe works, I think you're more interested in practicing inter-class relationships -- correct me if I'm wrong here. How about creating two classes: RandomObjectA and RandomObjectB. In both of these classes, define a set of variables, and then compare them within your main method. This will really help you understand how programming works on an object level, which is a much more important lesson than specific data constructs.

Once you've done that successfully, I would add some methods to each of your classes; how can you make it such that classes don't directly interact with attributes in other classes?

After that, I'd look into inheritance. What if we wanted to create 100 classes called RandomObjectX? It obviously wouldn't be reasonable to hand-code each and every last one, so let's think about how we can derive functionality from a higher-up class, called a superclass.

Lastly, while I appreciate that you're jumping in and trying things, I highly recommend that you read the Python tutorial and documentation. It's honestly not a hard read, you'll learn a ton, and you'll have a better scope of what exactly is going on when you code. If you combine hands-on practice and personal projects with reading documents, coding becomes much easier. Good luck!

Upvotes: 1

Related Questions