我不了解有關 Python、變數和函式的一些非常基本的知識。我試圖將一個函式存盤在一個物件的屬性中,然后檢索它并呼叫它。
def FilterHidden(path: pathlib.Path)->bool:
return path.name.startswith('.')
class Filter(object) :
dirFilterer=FilterHidden
fileFilterer=FilterHidden
def shouldFilter(s, path:pathlib.Path)->bool:
filterer=s.dirFilterer if path.is_dir() else s.fileFilterer
return filterer(path)
從錯誤中,我發現過濾器函式試圖用兩個引數呼叫:隱式自我和顯式路徑。
mypy: Invalid self argument to "Filter" to attribute "dirfilterer" with type "Callable[[Path],bool]
python: TypeError: FilterHidden() takes 1 positional argument but 2 were given
揭露我已經變老并且在使用新語言時遇到麻煩讓我感覺更好,因為沒有人想說“在 Python 內部,這就是發生的事情”。我覺得被簡化的理想誤導了。計算機不是概念性的;它們是遵循非常精確模式的計算器。
uj5u.com熱心網友回復:
s.dirFilterer回傳系結方法實體而不是 function FilterHidden。您可以使用靜態方法使其作業
>>> def foo():
... pass
...
>>> class Bar:
... f = foo
...
>>> b = Bar()
>>> b.f
<bound method foo of <__main__.Bar object at 0x7f04d0ad9430>>
>>>
>>> class Qux:
... f = staticmethod(foo)
...
>>> q = Qux()
>>> q.f
<function foo at 0x7f04d0a84d30>
uj5u.com熱心網友回復:
我假設您正在嘗試創建私有類屬性,python 沒有私有方法,您可以使用工廠模式來構建它,看看:
from pathlib import Path
def filter_factory(object):
#put your private methods here
def FilterHidden(path: Path)->bool:
return path.name.startswith('.')
class Filter(object) :
#put your public methods here
def shouldFilter(s, path:Path)->bool:
return FilterHidden(path)
return Filter()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/350616.html
