How to call a function within a class from another class

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Aaron Dingo

    How to call a function within a class from another class

    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

    Code:
    class Testclass1(object):
    
        def __init__(self, var1):
            self.printthis = var1
            
        def printthing(self):
            lookatme = self.printthis
            Testclass2(lookatme).printokay()
    
    class Testclass2(object):
        def __init(self, var2):
            self.okayletsprint = var2
    
        def printokay(self):
            print "this is text"
            print self.okayletsprint
    
    a = Testclass1("jumbo")
    a.printthing()
    Last edited by bvdet; Nov 13 '10, 01:36 PM. Reason: Edit title
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    You left out 2 underscore characters in Testclass2.__in it__(self).

    Comment

    • Aaron Dingo

      #3
      Rearranged

      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).

      Code:
      class Testclass1(object):
      
          def __init__(self, var1):
              self.printthis = var1
      
          def printthing(self):
              lookatme = self.printthis
              Testclass2.printokay(lookatme)
      
      class Testclass2(object):
          def __init__(self, var2):
              self.okayletsprint = var2
      
          def printokay(self):
              print "this is text"
              print self.okayletsprint
      
      a = "jumbo"
      Testclass1(a).printthing

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        In order to call function or a method of an instance, you must include the parentheses. Testclass1(a).p rintthing()

        Comment

        • Aaron Dingo

          #5
          Excellent, thank you. Ammended code is attached for anyone that has a similar problem.

          Code:
          class Testclass1(object):
          
              def __init__(self, var1):
                  self.printthis = var1
          
              def printthing(self):
                  Testclass2().printokay()
          
          class Testclass2(object):
              def __init__(self):
                  self.okayletsprint = 1
          
              def printokay(self):
                  print "this is text"
                  print self.okayletsprint
          
          
          a = Testclass1("jumbo bitch")
          a.printthing()

          Comment

          Working...