如何在python中调用class中的子函数?

How to call sub function in a class in python?

(我对 python 和 Whosebug 都很陌生。)

def A():
    def B():
        print("I'm B")
    A.B = B

A()
A.B()

输出:

"I'm B"

这很好用。我想要的是像这样把它放在 class 中(不起作用。我只是试过..)

class Student:
    def A(self):
        def B():
            print("I'm B")
        self.A.B = B

我不知道如何制作 class 以及如何调用 class 中的子函数。

您不需要引用 self,因为内部函数 B 已在那里定义。应该是这样的:

class Student:
    def A(self):
        def B():
            print("I'm B")
        B()

我从来没有用过类,但是你可以这样做吗?

class A:                       
    def __call__(self):          //  so you can call it like a function
        def B():               
            print("i am B")     
        B()

call_A = A()                     //  make the class callable
call_A()                         //  call it

Python 函数是 first-class objectsWhat is first class function in Python

所以第一段代码是完全有效的。它只是在函数中添加了一个 属性 B ,稍后可以使用 A.B().

调用它

但是对于第二段代码,这是无效的,因为self.A returns引用了class的A方法Student

<bound method Student.A of <__main__.Student object at 0x7f5335d80828>>

self.A 没有属性 B,所以它 returns 一个错误

AttributeError: 'method' object has no attribute 'B'

现在一个快速的解决方法是将它分配给 self.B

class Student:
    def A(self):
        def B():
            print("I'm B")
        self.B = B

a = Student()
a.A()
a.B()

虽然上面的代码有效,但这是一个非常糟糕的方法,因为在调用 B.

之前,您必须始终为每个实例化的对象调用 A