Methods with the same name in one class in Python

前端 未结 9 1647
执笔经年
执笔经年 2021-01-30 02:18

How can I declare a few methods with the same name, but with different numbers of parameters or different types in one class?

What must I change in the following class?

9条回答
  •  北恋
    北恋 (楼主)
    2021-01-30 02:46

    Python is nothing like Java.

    There are not really types, just objects with methods.

    There is a way to test if a passed object is from a class, but it is mainly bad practices.

    However, the code you want to produce for the two first methods should be something like

    class MyClass(object):
        def my_method(self, str1, str2=None):
            print str1
            if str2: print str2
    

    For the third, well... Use a different name...

提交回复
热议问题