方法的重载和动态性

在Python中,方法没有重载

在其他语言中,可以定义多个重名的方法,只要保证方法签名唯一即可。方法签名包含 3个部分:方法名、参数数量、参数类型
  而在Python 中,方法的参数没有声明类型,参数的数量也可以由可变参数控制。 因此,Python 中是没有方法的重载的。定义一个方法即可有多种调用方式,相当于实现了其他语言中的方法的重载。
如果我们在类体中定义了 多个重名的方法只有最后一个方法有效
在编程中最好不要使用重名的方法!Python 中方法没有重载。

class Person:
    def say_hi(self):
        print("hello")
    def say_hi(self,name):
        print("{0},hello".format(name))
p1 = Person()
# p1.say_hi() #只有最后一个带参数方法有效,所以报错,say_hi() missing 1 required positional argument: 'name'
p1.say_hi("LiMing")

运行结果:
LiMing,hello

方法的动态性

Python 是动态语言,我们可以动态的为类添加新的方法,或者动态的修改类的已有的方法。

class Person:
    def work(self):
        print("努力上班!")
def play_game(self):
        print("{0}玩游戏".format(self))
def work2(s):
        print("好好工作,努力上班!")

Person.play = play_game  #为类添加方法
Person.work = work2  #修改类中的方法
p = Person()
p.play()
p.work()

运行结果:
<__main__.Person object at 0x0000018316994F60>玩游戏
好好工作,努力上班!
我们可以看到,Person 动态的新增了 play_game 方法,以及用 work2 替换了 work 方法。

猜你喜欢

转载自blog.csdn.net/weixin_42205723/article/details/88410120
今日推荐