python 方法没有重载和方法的动态性

方法没有重载

方法的签名包含3个部分:

  • 方法名
  • 参数数量
  • 参数类型

python 方法的参数没有类型(调用时确定参数的类型),参数的数量也可以由可变参数控制。因此pyhton没有方法的重载;;

# python 没有方法的重载。定义多个同名方法,只有最后一个有效;;
class Student:

    def name(self):
        print('小明')
    
    def name(self,name):
        print('{0},hello'.format(name))

s1 = Student()
s1.name()

 方法的动态性

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

# 方法的动态性
class Student:
    def go(self):
        print('读书')
    

def bye_bye(b):
    print("{0}在睡觉".format(b))

# 给Student类,添加bye_bye方法 
Student.bye = bye_bye;

s = Student()
s.go()
s.bye()

 

# 方法的动态性
class Student:
    def go(self):
        print('读书')
    

def bye_bye(b):
    print("{0}在睡觉".format(b))

def work2(s):
    print('好好学习')

# 给Student,添加bye_bye方法 
Student.bye = bye_bye;

s = Student()
s.go()
s.bye()

Student.work = work2
s.work()

方法也是对象

Guess you like

Origin blog.csdn.net/qq_26086231/article/details/121459306
Recommended