代码之家  ›  专栏  ›  技术社区  ›  Ancient

在其他类内创建类的实例

  •  -1
  • Ancient  · 技术社区  · 6 年前

    我得像下面这样上课。

    class Reports()
    _name = 'reports'
    def fetch_transaction_invoice():
        #any logic here
    
     class Bar():
     _name = 'bar'
     def test_method():
         # here i want to access fetch_transaction_invoice of Reports class.
    

    但当我尝试跟随

    class Bar():
     _name = 'bar'
     def test_method():
         Reports.fetch_transaction_invoice ()
    

    它给了我以下的错误。

    TypeError: unbound method fetch_transaction_invoice() must be called with Reports instance as first argument (got nothing instead)
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Ray Salemi    6 年前

    通过使用 @classmethod 装饰师:

     class Reports():
        _name = 'reports'
        @classmethod
        def fetch_transaction_invoice(cls):
            print('fetched')
    
     class Bar():
        _name = 'bar'
        def test_method(self):
            Reports.fetch_transaction_invoice ()
    
     Bar().test_method()
    

    印刷品

     fetched
    

    (由于某些缩进问题,我不得不对您尝试的操作做一些假设。)