thicccjk
thicccjk

Reputation: 1

Initialise a class with objects of another class

say I have a class which describes a ball and its properties:

class Ball:
    def __init__(self, m=0.0,x=0.0, y=0.0):
        self.m = m
        self.x = x
        self.y = y
        self.r = np.array([x,y])
        
    def pos(self):
        print('Current position is:', self.r)  
            
    def move(self, x_move, y_move):
        x_moved = self.x+ x_move
        y_moved = self.y+ y_move
        r_moved = ([x_moved, y_moved])
        self.r = r_moved

How do i create another class which would initialise with objects from class Ball? And use methods from class Ball too?

I'm trying to create something like:

a = Ball(2,2,2)

class Simulation:
    def __init___('''object of Ball e.g. a''', r):

    def next_move(self):
        position_after_next_move = a.pos + '''method move from class Ball'''

I hope what I'm trying to say makes some sense.

Upvotes: 0

Views: 56

Answers (1)

quamrana
quamrana

Reputation: 39354

You are very close. You just need to pass the ball into the __init__() method and store it on the instance:

class Simulation:
    def __init___(self, ball, r):
        self.ball = ball
        ...

    def next_move(self):
        position_after_next_move = self.ball.pos()

a = Ball(2,2,2)
s = Simulation(a, 42)
s.next_move()

Upvotes: 2

Related Questions