Reputation: 1
I'm currently working on a task surrounding classes. In this task I have to create a class named "Balls". This class should have a init method that adds a self variable named position. This should be a list for x and y positions. After that I should create another class named System. This class should takes care of the main actions to perform. Then I have to implement a add ball method in System class that appends a Ball object to a class list inside System. Parameters in the method should be x and y.
class Ball:
def __init__ (self, x, y):
self.position = [x, y]
ball1 = Ball(3, 6)
print (ball1.position)
ball2 = Ball(5, 8)
print (ball2.position)
ball3 = Ball(4, 4)
print (ball3.position)
class System:
def __init__(self):
self.more_balls = []
def add_balls (self, x, y):
self.more_balls.append(Ball(x,y))
ballx = System()
ballx.add_balls(2, 4)
ballx.add_balls(5,5)
ballx.add_balls(8,8)
ballx.add_balls(2,4)
print (ballx.more_balls)
How will I be able to fix the code. The expected result is that balls get appended into the more_balls list. Here's the output I get:
[3, 6]
[5, 8]
[4, 4]
[<__main__.Ball object at 0x12308eb80>, <__main__.Ball object at 0x12308edf0>, <__main__.Ball object at 0x12308eeb0>, <__main__.Ball object at 0x12308e1f0>]
Upvotes: 0
Views: 125
Reputation: 489
I think is not responsibility of System
class to receive postion
s and instantiate Ball
objects.
So i would do it like this:
class Ball:
def __init__ (self, x, y):
self.position = [x, y]
class System:
def __init__(self):
self.more_balls = []
def add_ball (self, ball):
self.more_balls.append(ball)
ball1 = Ball(3, 6)
print (ball1.position)
ball2 = Ball(5, 8)
print (ball2.position)
ball3 = Ball(4, 4)
print (ball3.position)
ballHandler = System()
ballHandler.add_ball(ball1)
ballHandler.add_ball(ball2)
ballHandler.add_ball(ball3)
print (ballHandler.more_balls)
print (ballHandler.more_balls[0].position)
Upvotes: 0
Reputation: 5531
You have made a small mistake in the add_balls
function. You forgot to append the position
of the Ball
object. Here is how you rectify it:
def add_balls(self, x, y):
self.more_balls.append(Ball(x, y).position)
Thus, here is the full code:
class Ball:
def __init__(self, x, y):
self.position = [x, y]
ball1 = Ball(3, 6)
print(ball1.position)
ball2 = Ball(5, 8)
print(ball2.position)
ball3 = Ball(4, 4)
print(ball3.position)
class System:
def __init__(self):
self.more_balls = []
def add_balls(self, x, y):
self.more_balls.append(Ball(x, y).position)
ballx = System()
ballx.add_balls(2, 4)
ballx.add_balls(5, 5)
ballx.add_balls(8, 8)
ballx.add_balls(2, 4)
print(ballx.more_balls)
Output:
[3, 6]
[5, 8]
[4, 4]
[[2, 4], [5, 5], [8, 8], [2, 4]]
Upvotes: 1