在下面的代码中我试图实现继承和多态属性,我的问题是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")
Run Code Online (Sandbox Code Playgroud)
您正在尝试实现方法重载而不是继承和多态.
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")
Run Code Online (Sandbox Code Playgroud)