V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
yagamil
V2EX  ›  Python

在类内赋值一个类外的函数,会自动加了个 self 参数。

  •  
  •   yagamil · 2021-08-13 00:30:49 +08:00 · 800 次点击
    这是一个创建于 959 天前的主题,其中的信息可能已经有所发展或是发生改变。

    代码如下

    def myFun(*args,**kwargs):
        print('argument in myFun',args,kwargs)
        return True
    
    class OneArgumentSeries():
    
        def __init__(self, s1, s2):
            try:
                series = self.func(s1,s2)
            except Exception as e:
                raise ValueError(e)
            else:
                print(series)
    
    
    class ChildSeries(OneArgumentSeries):
    
        func=myFun
    
    
    obj = ChildSeries(s1='A',s2='B')
    

    结果如下:

    argument in myFun (<__main__.ChildSeries object at 0x00000000025E8130>, 'A', 'B') {}
    True
    

    self.func(s1,s2) 传了 2 个参数进去,实际调用的时候把 self 也传进去了。 好奇有什么操作可以只限定这两个参数,不传入 self ?

    frostming
        1
    frostming  
       2021-08-13 09:35:48 +08:00   ❤️ 1
    func = staticmethod(myFun)
    princelai
        2
    princelai  
       2021-08-13 09:39:03 +08:00   ❤️ 1
    func=staticmethod(myFun)
    yagamil
        3
    yagamil  
    OP
       2021-08-13 10:55:07 +08:00
    @frostming @princelai
    谢谢,可行。第一次这么用。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5338 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 08:09 · PVG 16:09 · LAX 01:09 · JFK 04:09
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.