如何从python中的类调用外部函数

GTh*_*izh 3 python-3.x

我如何从此类中调用外部函数?

def test(t):
   return t

class class_test():
   def test_def(q):
       test_msg = test('Hi')
       print (test_msg)
Run Code Online (Sandbox Code Playgroud)

Fer*_*dox 6

我对您的代码做了一些更改。self定义它们时,应将其用作类方法的第一个参数。object应该以类似的方式使用。

要调用类方法,可以创建该类的实例,然后调用该实例的属性(该test_def方法)。

def test(t):
    return t

class ClassTest(object):
    def test_def(self):
        test_msg = test('Hi')
        print(test_msg)

# Creates new instance.
my_new_instance = ClassTest()
# Calls its attribute.
my_new_instance.test_def()
Run Code Online (Sandbox Code Playgroud)

另外,您可以这样称呼:

ClassTest().test_def()
Run Code Online (Sandbox Code Playgroud)