跳转到内容
View in the app

A better way to browse. Learn more.

彼岸论坛

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.
欢迎抵达彼岸 彼岸花开 此处谁在 -彼岸论坛

[Python] functools.partial 和 partialmethod 的困惑

发表于
我在写一个 telegram bot ,自己寨了一个小的 lib
```
class Client:
def callAPI(self, method="getMe", **kwargs):
调用 requests.post(....)

getMe = functools.partialmethod(callAPI, "getMe")
```
这样是成功的,可以用 getMe=functools.partialmethod 的方法定义一个名为 getMe 但实际上偏函数调用 callAPI 的方法


但是另外几种写法都不对,我不明白为什么:
第一个:
```
def __getattr__(self, APIname):
return functools.partialmethod(callAPI, APIname)
```
会导致错误
NameError: name 'callAPI' is not defined
我不明白为什么 getMe 直接赋值的时候可以找到 callAPI 方法,但是在__getattr__函数里就找不到 callAPI 方法,必须用 self.callAPI 的方式来找。是不是因为前者在 class 内,而后者在 method 内的,scope 不同的缘故?

第二个:
```
def __getattr__(self, APIname):
return functools.partialmethod(self.callAPI, APIname)
```
c=Client(token="....")
c.getMe()会发生
TypeError: 'partialmethod' object is not callable

但是
c.getMe.func()
就可以正常执行

我不明白,为什么直接用 partialmethod 赋值出来那个函数就是 callable 的,但这里用__getattr__返回的却不是 callable 的呢

最后找到正确写法是:
```
def __getattr__(self, APIname):
return functools.partial(self.callAPI, APIname)
```
但是该用 partialmethod 的地方用了 partial ,总感觉不正经

Featured Replies

No posts to show

创建帐户或登录来提出意见

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.