簡體   English   中英

將模塊方法分配給Class變量或Instance變量

[英]Assign module method to a Class variable or Instance variable

在模塊a.py中

def task(): 
    print "task called"

a = task

class A:

    func = task              # this show error unbound method
    #func = task.__call__    # if i replace with this work

    def __init__(self):
        self.func_1 = task

    def test_1(self):
        self.func_1()

    @classmethod
    def test(cls):
        cls.func()


a()
A().test_1()
A.test()

輸出:

task called
task called
Traceback (most recent call last):
  File "a.py", line 26, in <module>
     A.test()
  File "a.py", line 21, in test
     cls.func()
TypeError: unbound method task() must be called with A instance as 
first argument (got nothing instead)

在模塊中,我可以輕松地將函數分配給變量。 當在類內部嘗試將模塊級功能分配給類變量func = task時,它顯示錯誤,要消除此錯誤,我必須將其替換為func = task .__ call__,但是當我將其工作分配給實例變量self.func_1 = task時

我的問題是:為什么沒有__call__不能將模塊級別的函數分配給類變量, 並且可以分配給實例變量的相同函數正在起作用。

因為您將函數映射為A未綁定方法,所以當您調用cls.func ,首先要詢問等於getattr(cls, 'func') ,該getattr(cls, 'func')返回<unbound method A.task> BUT,但此unbound方法需要以class作為第一個參數調用。

因此,因為在這種特定情況下, cls.func意思是“賦予我cls類屬性func ”,所以它不能同時表示“調用類的方法func ”-因此Python不會通過func(cls)翻譯cls.func() 。 。

但是同時,由於func<unbound method A.task> (綁定到A.task ),因此需要像func(cls)一樣func(cls)它才能工作。

用類似的方法檢查它:

@classmethod
def test(cls):
    print getattr(cls, 'func') # <unbound method A.task>

您可以使用以下方法修復它:

def task(cls=None):
    if cls is None:
        print 'task()'
    else:
        print 'A.foo({})'.format(cls)

a = task

class A:
    func = task             # this show error unbound method

    def __init__(self):
        self.func_1 = task

    def test_1(self):
        self.func_1()

    @classmethod
    def test(cls):
        cls.func(cls())

a()
A().test_1()
A.test()

輸出:

task()
task()
A.foo(<__main__.A instance at 0x7fd0310a46c8>)

請注意,python3刪除了未綁定的方法,這僅適用於python2.x

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM