DaCR
DaCR

Reputation: 19

Class To Number

I'm a rookie. I have a question about class. Here's my code:

class randcolour:
    def randc(self):
        self.r = random.randint(0, 255)
        self.g = random.randint(0, 255)
        self.b = random.randint(0, 255)
        return (self.r, self.g, self.b)

colour = randcolour()
colour2 = randcolour()
colour3 = randcolour()
colour4 = randcolour()

But it said"TypeError: invalid color argument" How can I do? int(randcolour)?

Upvotes: 1

Views: 64

Answers (4)

formatkaka
formatkaka

Reputation: 1358

This is what you are trying to implement.

import random 

class RandColor(object):

def randc(self):
    self.r = random.randint(0,255)
    self.g = random.randint(0,255)
    self.b = random.randint(0,255)
    return (self.r,self.g,self.b)

color = RandColor()
color.randc()

print color.r

Rather than this , I prefer you try using init method

import random

class RandColour:
def __init__(self):
    self.r = random.randint(0,255)
    self.g = random.randint(0,255)
    self.b = random.randint(0,255)

def return_colour(self):
    return (self.r, self.g, self.b)

color = RandColour()

The object gets initialised directly.

To obtain the values

color.return_colour()

Upvotes: 1

nicedi
nicedi

Reputation: 13

your RandColour class(capitalize first character of each word by convention) should be:

import random
class RandColour:
    def __init__(self):
        self.r = random.randint(0,255)
        self.g = random.randint(0,255)
        self.b = random.randint(0,255)

    def get_colour(self):
        return (self.r, self.g, self.b)

then you can create a RandColour object and get the random colour:

c = RandColour()
c.get_colour()

initialization of instance variable should be performed in the init function.

Upvotes: 1

Jesse Bakker
Jesse Bakker

Reputation: 2623

What you are doing is creating a class with a method and then instantiating the class. For such a simple object, it should be enough to just use a function. I would do this:

def randcolour():
    return (random.randint(), random.randint(), random.randint())

which is a function that returns a tuple with 3 random values.

Upvotes: 1

Matt Messersmith
Matt Messersmith

Reputation: 13747

You don't have an __init__ for your class. This means when you say

coulor = randcolour()

your randc function never gets called. If you replace

def randc(self):

with

def __init__(self):

you will probably get the desired behavior (although your question isn't totally clear, so this may not be what you want).

Another way to make sure your fields are getting set would be to change your calls to be like this:

colour = randcolour().randc()

The big take-away is that self.r, self.g, and self.b are never being set in the driver code you've provided.

Upvotes: 0

Related Questions