Search code examples
pythonclasspython-2.7argsoptional-arguments

Set a custom class as an optional argument's type to a method within that class


tl;dr: I want to know how to set an optional argument's type to a custom built class, i.e;

Code:

class Point(object):
    def __init__(self,x=int,y=int):   # Initialize Point object with optional args
        self.val=(x,y)
    def __add__(self,p=Point):        # p=Point is the issue
        ...

I've tried:

def __add__(self,p=self.__class__):  # Cannot reference self in an arg.
def __add__(self,p=Point):           # Point is not defined

Long story:

I've done several searches that found nothing so far, but I think its more the terms I'm using.

I'm building a 2d Point/Vector class (I know, been done already, but I'm learning, and developing my writing style.), and I've developed an aversion to using untyped positional args in most cases, mainly for ease of maintenance.

I haven't been able to figure out how to set an optional arg's type to a custom built class, such as Point above, instead of one of python's built in types.

Note: I'm aware that simply making p a positional arg would work, and it does, but as long as there is no main reason not to do things this way, other than it being slightly rigid for python's philosophy, I'd like to type the args for clarity of code.

How can that be accomplished, is it worth it, and are there any cons to doing things this way?

Any tips on best practices for this type of thing are greatly welcome as well.


Solution

  • I think you may be misunderstanding what x=int and y=int are doing in your code.

    class Point(object):
        def __init__(self,x=int,y=int):   # Initialize Point object with optional args
        ...
        def __add__(self,p=Point):  
    

    Creating an instance of Point,

    u = Point()
    

    would produce an object u. The optional arguments x and y will be equal to the Python object that represents the int type not integers (here distinguish between integers like 1, 3, 99 and their type=int). In general, using the equals sign in function arguments specifies a default value not a type. Likewise, if the argument p is not passed to the function add, p will be equal to the object that represent the class Point. It will not make p an instance of the class Point. You cannot specify in advance the type of function arguments. In addition their types can be changed inside the function. This is because Python is a dynamically typed language.

    This page on duck typing might help clarify things. If you like, you can check the type of the arguments after they are passed in and act on that information, but the basic idea is, if it walks like an int and talks like an int, who cares if its actual type is int.

    The Python section of the duck typing article leads to a description of exceptions in Python and their suggested use in these situations.