使用两个必需参数定义python函数的最佳方法,其中一个可以有两种类型之一?

时间:2017-09-19 19:05:06

标签: python

我有一个方法collide,它接受​​:

  • 一个Ball - 物体和int并计算球撞墙后的速度,或
  • 两个球对象并在它们相互碰撞后计算它们的速度。

我的功能如下:

def collide(self, ball_1, arg2): 
    """Takes {one ball and a wall} or {two balls} and sets their velocities to the correct ones for after the collision.

    ball_1 is an instance of ball

    arg2 is either Ball or int (wall_no)

    collide sets the new velocities for two balls colliding or for one ball colliding with a wall.
    """


    if not isinstance(ball_1, Ball):
        ArgumentError("ball_1 must be Ball")

    if not (isinstance(arg2, int) or isinstance(arg2, Ball)):
        ArgumentError("ball_2 must be int or Ball")

    if isinstance(arg2, int): ## CHECKING IF int

        wall_no = arg2

        ### Changing the velocity of the sole ball ###

    elif isinstance(arg2, Ball): ## CHECKING IF Ball
        ball_2 = arg2

    ### Loads of linear algebra and mechanics ###

    else:
        raise ValueError('Invalid arguments')

我想知道在这种情况下处理函数参数的最佳实践是什么。我不是真的想要一个可能是两种不同类型之一的论点。推荐的做法是什么?

编辑:

class Board:

    def __init__(self, width = 100, height = 100, sps = 2):     
        """A board with (x,y) = (0,0) in the bottom left corner, 
        like the first quadrant of a coordinate system.

        width, height; no of cells
        sps; steps per second
        step_size; step size in terms of time. unit: seconds.
        """
        self.width = width
        self.height = height
        self.sps = 2
        self.timestep = 1/sps
        self.balls = set()
    def collide():
        #...

1 个答案:

答案 0 :(得分:1)

我个人会根据你的Ball类进行碰撞,并做这样的事情:

class Ball:
    def collide(self, other):
        if isinstance(other, Ball):
            self.collideWithBall(other)
            other.collideWithBall(this) #might not want this line, depending on how you're organizing the logic.
        elif isinstance(other, int):
            self.collideWithWall(other)
        else:
            #error here

    def collideWithBall(self, otherBall):
        ### Loads of linear algebra and mechanics ###

    def collideWithWall(self, wallId):
        ### Changing the velocity of the sole ball ###