推荐学习书目
› 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 · Aug 13, 2021 · 1602 views
    This topic created in 1871 days ago, the information mentioned may be changed or developed.

    代码如下

    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  
       Aug 13, 2021   ❤️ 1
    func = staticmethod(myFun)
    princelai
        2
    princelai  
       Aug 13, 2021   ❤️ 1
    func=staticmethod(myFun)
    yagamil
        3
    yagamil  
    OP
       Aug 13, 2021
    @frostming @princelai
    谢谢,可行。第一次这么用。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2468 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 15:41 · PVG 23:41 · LAX 08:41 · JFK 11:41
    ♥ Do have faith in what you're doing.