简体   繁体   English

如何在python中的类之间使用函数

[英]How to use functions between classes in python

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? 如果我在python脚本中有多个类,该如何从第二个类的第一个类调用函数?

Here is an Example: 这是一个例子:

Class class1():

  def function1():
        blah blah blah

Class class2():

 *How do I call function1 to here from class1*

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: 从class2调用class1中的方法的方法是拥有class1的实例:

class Class2(object):
    def __init__(self):
        self.c1 = Class1()
        self.c1.function1()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM