开发者

What would be the proper way of handling arguments for a method that could be ints or chars in python?

For example, I want to have a method that, depending on the first argument passed, can take either an i开发者_JAVA技巧nt or a char as the second argument.

The way I thought of doing it is to have an if right after the method it calls to check what the first argument is, it can be one of 4. At this point, if it's of say, type 1 or 2 that expects an int as the second argument, it completes the code within the if. I then have an elif checking if the first argument is of type 3 or 4, then it goes into that block and completes the code within that block. The else will throw an exception or handle the issue accordingly.

Is this the right way to do it?


You better have two different methods if inner code is different in both cases.


If the code is same, with some transformation of parameteres (getting ASCII value of char for example - btw, char in python is just a string with length of 1), you should do the cast at the start of function and the rest of the code should be the same. For example:

def foo(a, b):
    if a == 1:
        b = ord(b)
    # use b as if it is integer

If the rest of the code is totaly different you sholud be writing different functions and not trying to squeeze it in one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜