Skip to main content
 首页 » 编程设计

python之继承和多态性

2025年05月04日13tintown

在下面的代码中,我试图实现继承和多态性属性,我的问题是 obj1.hello3("1param","2param") obj1.hello3("11param") 是这些语句不正确,正确的做法是什么

  #!/usr/bin/python 
 
  class test1: 
     c,d = "" 
     def __init__(self,n): 
        self.name = n 
        print self.name+"==In a" 
     def hello1(self): 
        print "Hello1" 
     def hello3(self,a,b): 
        #print "Hello3 2 param"+str(a)+str(b) 
        #print "ab"+str(self.a)+str(self.b)+"Hello1" 
        print "Hello3 2 param" 
 
     def hello3(self,a): 
        #print "a"+str(self.a)+"Hello1" 
        print "Hello3 1 param"+str(a) 
 
  class test2(test1): 
     def __init__(self,b): 
        test1.__init__(self, "new") 
        self.newname = b 
        print self.newname+"==In b" 
     def hello2(self): 
        print "Hello2" 
 
  obj= test1("aaaa") 
  obj1=test2("bbbb") 
  obj1.hello1() 
  obj1.hello2() 
  obj1.hello3("1param","2param") 
  obj1.hello3("11param") 

请您参考如下方法:

您正在尝试实现方法重载而不是继承和多态性。

Python 不像 C++、Java、C# 等那样支持重载。相反,要在 Python 中实现您想要的,您需要使用可选参数。

def hello3(self,a,b=None): 
    if b is None: 
        print "Hello3 1 param", a 
    else: 
        print "Hello3 2 param", a, b 
 
... 
 
obj1.hello3("a")#passes None for b param 
obj1.hello3("a", "b")