2011-08-12 25 views
1

在下面的代码我想实现继承和多态特性,我的问题是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") 
+0

python中不支持方法重载吗? – Rajeev

回答

5

你试图实现方法重载而不是继承和多态。

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") 
1

Python不会有方法超负荷,所以

def hello3(self,a): 
    #print "a"+str(self.a)+"Hello1" 
    print "Hello3 1 param"+str(a) 

只是取代以上定义的hello3方法。还要注意,就C++而言,Python类中的所有方法都是“虚拟的”,所以多态性总是在这里。

也由行aa.__init__(self, "new")您可能意味着test1.__init__(self, "new")

+0

所以你说的是hello3(“a”)和hello(“a”,“b”)会是错的吗? – Rajeev

+0

@Rajeev是的。在Python中阅读一些关于类和OOP的书籍和文章。在StackOverflow中学习这些一般的东西是一个坏主意。 –

+0

嘿,我找不到任何例子或书籍,以便这个wud是最好的地方问它。 – Rajeev

0

那么首先你有一个像一些编码问题: c,d = ""或随机sel有或aa.__init__(self, "new")

我不知道这是来自快速键入还是这是您的实际代码。在test2 __init__方法中,正确的呼叫是test1.__init__(self, "new")

也作为编码风格,你应该用camelcase写一个大写字母的类,例如:Test1,MyNewClass

这些调用是正确的,但python不支持以java的方式重载。所以多个def hello3(...应该给你一个duplicate signature

+0

是的,我已经纠正它,快速搭售......是的.. – Rajeev

+0

所以你说那里的方法重载不支持python ..? – Rajeev

+0

正确 - 没有java或C++式的重载。你可以通过'def hello(a,b = None)'来做到这一点,然后对'b'做一个测试来根据它的存在来改变行为。 –

1

您可以使用* args或** kwargs。请参阅examples and explanations

class test1: 
    def __init__(self): 
     print 'init' 
    def hello(self, *args): 
     if len(args) == 0: 
      print 'hello there' 
     elif len(args) == 1: 
      print 'hello there 1:',args[0] 
     elif len(args) == 2: 
      print 'hello there 2:',args[0],args[1] 

class test2: 
    def __init__(self): 
     print 'init' 
    def hello(self, **kwargs): 
     if len(kwargs) == 0: 
      print 'hello there' 
     elif 'a' in kwargs and 'b' not in kwargs: 
      print 'hello there a:', kwargs['a'] 
     elif 'a' in kwargs and 'b' in kwargs: 
      print 'hello there a and b:', kwargs['a'], kwargs['b'] 
+0

非常感谢........................ – Rajeev