【问题标题】:How to access class method within class but outside class methods or member functions? [duplicate]如何在类内访问类方法,但在类方法或成员函数外访问? [复制]
【发布时间】:2020-06-02 06:33:12
【问题描述】:

说,代码是

class A():
    @staticmethod
    getB():
        return ['B', 'BB']

    list_B = A.getB()

如何在任何函数之外的类中访问函数 B()?在代码 sn-p 中,A 未被识别为有效的变量/类。

【问题讨论】:

  • @Rohith。您的代码中有错误尝试先修复它。

标签: python python-3.x


【解决方案1】:

你有两种可能:

  • 使用getB.__func__()
  • 在类的另一个函数中使用A.getB()

试试这个:

class A():
    @staticmethod
    def getB():
        return ['B', 'BB']

    list_B = getB.__func__()
    print("list_B_1", list_B)

    def foobar(self):
        list_B_2 = A.getB()
        print("list_B_2", list_B_2)

a = A()
a.foobar()

【讨论】:

    猜你喜欢
    • 2019-10-15
    • 2012-09-16
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-29
    • 2012-11-06
    • 2020-12-05
    相关资源
    最近更新 更多