我在 Python 中定義了一個球類,如下所示,它初始化為質量 = 1,半徑 = 1,然后我們可以將其位置和速度向量設定為 2d numpy 陣列。
class Ball():
def __init__(self, pos = np.array([0,0]), vel = np.array([0,0]), mass = 1, radius = 1):
self.mass = mass
self.radius = radius
self.pos = pos
self.vel = vel
我還有一個Ball的子類,叫做Container,本質上是一個半徑為10的大球,如下:
class Container(Ball):
def __init__(self, radius = 10):
self.radius = radius
ball 類還有三個方法,我想在一個名為 Simulation 的新類中使用它們。這些方法在 ball 類中定義,如下(引數 other 只是與自身球碰撞的另一個球):
def move(self, dt):
self.dt = dt
return np.add((self.pos),(np.dot((self.vel),self.dt)))
def time_to_collision(self, other):
self.other = other
self.posdif = np.subtract(self.pos, other.pos)
self.veldif = np.subtract(self.vel, other.vel)
self.posdif = np.subtract(self.pos, other.pos)
self.veldif = np.subtract (self.vel, other.vel)
self.raddif = self.radius - other.radius
return (-2*np.dot(self.posdif, self.veldif) np.sqrt(4*(np.dot(self.posdif, self.veldif)**2)-4*np.dot(self.veldif, self.veldif)*(np.dot(self.posdif, self.posdif)-np.dot(self.raddif, self.raddif))))/(2*np.dot(self.veldif, self.veldif))
def collide(self, other):
self.other = other
return self.vel - (np.dot(self.veldif, self.posdif)*self.posdif)/(np.dot(self.posdif,self.posdif))
為長計算道歉,但我認為計算線不一定與問題相關,只是為了完整性而將其包括在內。這些方法、move、time_to_collision和collide將在另一個類中使用,模擬。模擬類定義如下:
class Simulation():
def __init__(self, ball = Ball(), container = Container()):
self._container = container
self._ball = ball
def next_collision(self):
return self._ball.move(self._ball.time_to_collision(self._ball, self._container))
The simulation class aims to be initialised with a Ball object, and a Container object. It then has a method, next_collision, (with the only parameter being self) which uses the methods time_to_collision to work out the time between the collision of the ball and the container, and then it will use move to move the system to that moment in time, and then perform the collision using collide. The situation looks like this if a visualisation might help:

I have tried to achieve this in my next_collision(self): method, but I am always getting the same type error:
TypeError: time_to_collision() takes 2 positional arguments but 3 were given
uj5u.com熱心網友回復:
你的next_collision方法只需要兩個引數,你傳遞了三個,就像錯誤所說的那樣。
self當您在物件上呼叫方法時,引數會自動傳遞。所以你應該用它self._ball.time_to_collision(self._container)來實作你想要的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/356496.html
標籤:python class oop methods physics
上一篇:為什么我們可以呼叫來自Java中另一個執行緒的物件的方法?
下一篇:類的C 模板
