By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,621 Members | 1,077 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,621 IT Pros & Developers. It's quick & easy.

Using methods of other classes in a class

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

Expand|Select|Wrap|Line Numbers
  1. class A:
  2.     def __init__(self, x, y):
  3.         self.x = x
  4.         self.y = y
  5.  
  6. class B(A):
  7.     def __init__(self, x, y, z):
  8.         self.z = z
  9.  
  10.     def add(self):
  11.         result = self.x + self.y + self.z
  12.  
  13. class C(B):
  14.     def __init__(self, x):
  15.         self.x = x
  16.  
  17.     while 1==1:
  18.         B.add()
  19.         result += self.x
  20.         print result
  21.  
  22.  
  23. A = A(1,2)
  24. B = B(1,2,3)
  25. C = C(1)
Mar 25 '09 #1
Share this Question
Share on Google+
2 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
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.
Expand|Select|Wrap|Line Numbers
  1. class A(object):
  2.     def __init__(self, x, y):
  3.         self.x = x
  4.         self.y = y
  5.  
  6. class B(A):
  7.     def __init__(self, x, y, z):
  8.         self.z = z
  9.  
  10.     def add(self):
  11.         self.result = self.x + self.y + self.z
  12.  
  13. class C(B):
  14.     def __init__(self, x,y,z):
  15.         self.x = x
  16.         self.y = y
  17.         self.z = z
  18.         self.add()
  19.         self.result += self.x
  20.         print self.result
  21.  
  22.  
  23. a = A(1,2)
  24. b = B(1,2,3)
  25. c = C(1,2,3)
Mar 25 '09 #2

P: 9
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.
Mar 25 '09 #3

Post your reply

Sign in to post your reply or Sign up for a free account.