1

If I have more than one class in a python script, how do I call a function from the first class in the second class?

Here is an Example:

Class class1():

  def function1():
        blah blah blah

Class class2():

 *How do I call function1 to here from class1*
5
  • If you really need the functionality int class2 from class1 it would make more sense to put it into class2 instead, but I realize that this isn't part of your question but rather more some information. Commented Jul 18, 2012 at 3:41
  • I need the function in both classes Commented Jul 18, 2012 at 3:43
  • 1
    A more concrete example would help clarify your intention. Commented Jul 18, 2012 at 3:46
  • 2
    Ah, in that case in my opinion it would make more sense to not put the function in either class but have it on its own. Commented Jul 18, 2012 at 3:46
  • Questions like this reflect a fundamental misunderstanding. Classes are not simply containers for functions; they're blueprints for objects. Commented Jul 18, 2012 at 7:38

2 Answers 2

1

Functions in classes are also known as methods, and they are invoked on objects. The way to call a method in class1 from class2 is to have an instance of class1:

class Class2(object):
    def __init__(self):
        self.c1 = Class1()
        self.c1.function1()
Sign up to request clarification or add additional context in comments.

Comments

0

The cleanest way is probably through inheritance:

class Base(object):
    def function1(self):
        # blah blah blah

class Class1(Base):
    def a_method(self):
        self.function1()  # works

class Class2(Base):
    def some_method(self):
        self.function1()  # works

c1 = Class1()
c1.function1()  # works
c2 = Class2()
c2.function1()  # works

1 Comment

i think you mean c2.function1()

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.