python使用另一个类中的类的输出

时间:2015-04-10 11:31:36

标签: python class inheritance

我有下面描述的代码结构,它由两个类组成。我想要做的是使用classname1中返回的值及其在classname2中的所有方法。 我很感激你的帮助。

class   classname1(someObject):

      def __init__(self, someInput1):
           self.someInput = someInput

      def someMethod (self):
          'code '
          return something

class  classname2(someObject):

       def init(self, someInput2)
            self.someInput2 = someInput2

       def AnotherMethod(self):

       use the returned value from the first class  

2 个答案:

答案 0 :(得分:2)

不是将值返回到第2类,而是可以:
       在第1类和第1类中创建第2类的实例将返回值作为参数传递给类2中的函数。

例如:

class   classname1(someObject):
      def __init__(self, someInput1):
           self.someInput = someInput
      def someMethod (self):
          'code '
          //here create instance/object of class 2 
          //pass the return value to another method of class 2  

class  classname2(someObject):
       def init(self, someInput2)
            self.someInput2 = someInput2
       def AnotherMethod(self):
        // here receive the return value (from class 1) as one of the arguments.

或者你可以反之亦然:

class   classname1(someObject):
      def __init__(self, someInput1):
           self.someInput = someInput
      def someMethod (self):
          'code '

class  classname2(someObject):
       def init(self, someInput2)
            self.someInput2 = someInput2
       def AnotherMethod(self):
        //here create instance/object of class 1 
        //val num=class1Object.someMethod() 

祝你好运!

答案 1 :(得分:1)

通过

获取Classname1Inherit的所有方法
class Classname2(Classname1):

例如

class A:

    def __init__(self, someInput1):
        self.someInput1 = someInput1

    def someMethod1(self):
        return "something1"       


class B(A):

    def __init__(self, someInput2):
        self.someInput2 = someInput2

    def someMethod2(self):
        return "something2"


temp1 = B("ccc")
print(temp.someMethod1())
print(temp1.someMethod2())

#output
something1
something2

class A

中调用class B的方法
class B(A):

    def __init__(self, someInput2):
        self.someInput2 = someInput2

    def someMethod2(self):
        return self.someMethod1() # someMethod1 is method of A which is inherited to B

希望这有帮助