qing zhangqing
qing zhangqing

Reputation: 401

How to define a class function and print only numbers

I am working a class call MarbleBoard and my code is below :

class MarblesBoard:
    def __init__(self, balls):
        self.balls=balls
        print (self.balls)

board = MarblesBoard((3,6,7,4,1,0,8,2,5)) 

The reasult I got is:

(3, 6, 7, 4, 1, 0, 8, 2, 5)

But I want to get the result below

board = MarblesBoard((3,6,7,4,1,0,8,2,5)) 
board 
3 6 7 4 1 0 8 2 5 

Upvotes: 0

Views: 80

Answers (2)

carlos_fab
carlos_fab

Reputation: 18

Once you are workin with a class, you can use the __repr__ method to compute the "oficial" string reputation of an object:

class MarblesBoard():
    def __init__(self, balls):
        self.balls = balls

    def __repr__(self):
        return " ".join(str(i) for i in self.balls)

Now, when you call the board variable you get this output:

board = MarblesBoard((3,6,7,4,1,0,8,2,5))
board
3 6 7 4 1 0 8 2 5

Upvotes: 0

Brian Amadio
Brian Amadio

Reputation: 74

Rather than printing in the __init__ method, you should define a __repr__ method for your class.

For example:

def __repr__(self):
    return ' '.join([str(ball) for ball in self.balls])

Then you can do:

board = MarblesBoard((3,6,7,4,1,0,8,2,5)) 
print(board)
3 6 7 4 1 0 8 2 5

Upvotes: 2

Related Questions