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

How to call a function within a class from another class

P: n/a
Hi there,

could you help me spot my error - I'm sure it's a simple one. I'm just trying to understand classes in Python a little better (working through Learn Python The Hard Way).

Basically I want the printokay function in Testclass2 to run after being called from Testclass1

Expand|Select|Wrap|Line Numbers
  1. class Testclass1(object):
  2.  
  3.     def __init__(self, var1):
  4.         self.printthis = var1
  5.  
  6.     def printthing(self):
  7.         lookatme = self.printthis
  8.         Testclass2(lookatme).printokay()
  9.  
  10. class Testclass2(object):
  11.     def __init(self, var2):
  12.         self.okayletsprint = var2
  13.  
  14.     def printokay(self):
  15.         print "this is text"
  16.         print self.okayletsprint
  17.  
  18. a = Testclass1("jumbo")
  19. a.printthing()
  20.  
Nov 13 '10 #1
Share this Question
Share on Google+
4 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
You left out 2 underscore characters in Testclass2.__init__(self).
Nov 13 '10 #2

P: n/a
okay, underscores are included - thanks for spotting that.

I've been changing it around and now when I run this it still doesn't print (no error messages - nada).

Expand|Select|Wrap|Line Numbers
  1. class Testclass1(object):
  2.  
  3.     def __init__(self, var1):
  4.         self.printthis = var1
  5.  
  6.     def printthing(self):
  7.         lookatme = self.printthis
  8.         Testclass2.printokay(lookatme)
  9.  
  10. class Testclass2(object):
  11.     def __init__(self, var2):
  12.         self.okayletsprint = var2
  13.  
  14.     def printokay(self):
  15.         print "this is text"
  16.         print self.okayletsprint
  17.  
  18. a = "jumbo"
  19. Testclass1(a).printthing
  20.  
Nov 13 '10 #3

bvdet
Expert Mod 2.5K+
P: 2,851
In order to call function or a method of an instance, you must include the parentheses. Testclass1(a).printthing()
Nov 13 '10 #4

P: n/a
Excellent, thank you. Ammended code is attached for anyone that has a similar problem.

Expand|Select|Wrap|Line Numbers
  1. class Testclass1(object):
  2.  
  3.     def __init__(self, var1):
  4.         self.printthis = var1
  5.  
  6.     def printthing(self):
  7.         Testclass2().printokay()
  8.  
  9. class Testclass2(object):
  10.     def __init__(self):
  11.         self.okayletsprint = 1
  12.  
  13.     def printokay(self):
  14.         print "this is text"
  15.         print self.okayletsprint
  16.  
  17.  
  18. a = Testclass1("jumbo bitch")
  19. a.printthing()
  20.  
  21.  
Nov 13 '10 #5

Post your reply

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