Methods with the same name in one class in Python

前端 未结 9 1663
执笔经年
执笔经年 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:48

    class MyClass:
        def __init__(this, foo_str, bar_int):
            this.__foo = foo_str
            this.__bar = bar_int
    
        def foo(this, new=None):
            if new != None:
                try:
                    this.__foo = str(new)
                except ValueError:
                    print("Illegal value. foo unchanged.")
    
            return this.__foo
    
        def bar(this, new=None):
            if new != None:
                try:
                    this.__bar = int(new)
                except ValueError:
                    print("Illegal value. bar unchanged.")
    
            return this.__bar
    
    obj = MyClass("test", 42)
    print(obj.foo(), obj.bar())
    
    print(obj.foo("tset"), obj.bar(24))
    
    print(obj.foo(42), obj.bar("test"))
    
    Output:
        test 42
        tset 24
        Illegal value. bar unchanged.
        42 24
    

提交回复
热议问题