Using methods of other classes in a class

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • GKRAFT
    New Member
    • Nov 2008
    • 9

    Using methods of other classes in a class

    I want to know how I can (in a class) use another class' method.
    Here's an example (which is not working):

    Code:
    class A:
        def __init__(self, x, y):
            self.x = x
            self.y = y
    
    class B(A):
        def __init__(self, x, y, z):
            self.z = z
    
        def add(self):
            result = self.x + self.y + self.z
    
    class C(B):
        def __init__(self, x):
            self.x = x
    
        while 1==1:
            B.add()
            result += self.x
            print result
        
    
    A = A(1,2)
    B = B(1,2,3)
    C = C(1)
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Class object A should inherit from object to take advantage of the features of new style classes. Classic classes are likely to be deprecated in the future.

    You are in effect redefining class objects A, B and C by assigning an instance of the respective classes to those identifiers.

    Since an instance of class C has no y or z attribute, the method call to self.add() will fail.

    I cannot tell what you are trying to accomplish, but I modified your example so it would actually produce a result.
    Code:
    class A(object):
        def __init__(self, x, y):
            self.x = x
            self.y = y
     
    class B(A):
        def __init__(self, x, y, z):
            self.z = z
     
        def add(self):
            self.result = self.x + self.y + self.z
     
    class C(B):
        def __init__(self, x,y,z):
            self.x = x
            self.y = y
            self.z = z
            self.add()
            self.result += self.x
            print self.result
     
     
    a = A(1,2)
    b = B(1,2,3)
    c = C(1,2,3)

    Comment

    • GKRAFT
      New Member
      • Nov 2008
      • 9

      #3
      Thanks alot!
      I'm not really trying to acomplish anything with this code in particular, just used it as an example to find out how this could be done.

      Comment

      Working...