V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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
cc7756789
V2EX  ›  Python

Python 类中的一个函数的值如何通过 for 循环传递给另一个函数?

  •  
  •   cc7756789 · May 24, 2015 · 4287 views
    This topic created in 3991 days ago, the information mentioned may be changed or developed.
    class A(obejct):
        def all_answer(self):
            #somecode
            for s in br2n.split('\n'):
                yield re.sub(re_allmark, '', s)
    
        def save(self, path, pattern):
            if not path:
                raise 'No path'
            else:
                with open(path, pattern) as f:
                    f.write()
    

    大致的效果
    a = A()
    for each in a.all_answer():
    print each #正常返回结果
    each.save('/Path/', 'pattern') #保存到文件中

    如何让类中all_anser的值传入类中另一个函数呢?

    5 replies    2015-05-24 13:15:28 +08:00
    horizon
        1
    horizon  
       May 24, 2015
    self啊,你在all_answer中把想要传的值保存到self中,然后在save中使用就行了吧。
    oott123
        2
    oott123  
       May 24, 2015 via Android
    不应该是 a.save(each, path, pattern) 么…
    cc7756789
        3
    cc7756789  
    OP
       May 24, 2015
    answers = question.all_answer()
    question.save(answers, '/home/zhg/Pictures/result.txt', 'w')
    但是这种似乎不太人性化啊
    期望的效果是
    answers.save(....)
    dddd
        4
    dddd  
       May 24, 2015
    for s in br2n.split('\n'): self.save(...)

    OR:

    def save(path, mode):
    ----with open(path, mode) as f:
    --------for data in self.all_answer():
    ------------self.write(data)

    OR:

    def save(path, mode):
    ----answers = self.all_answer()
    ----with open(path, mode) as f:
    --------while 1:
    ------------try:
    ----------------data = answers.next()
    ----------------f.write(data)
    ------------except StopIteration:
    ----------------break
    dddd
        5
    dddd  
       May 24, 2015
    我懂你意思了。。。。

    class A(obejct):
    ----def all_answer(self):
    --------for s in br2n.split('\n'):
    ------------yield B(re.sub(re_allmark, '', s))

    class B(object):
    ----def __init__(self, data):
    --------self._data = data

    ----def save(self, path, pattern):
    ------------with open(path, pattern) as f:
    ----------------f.write(self._data)

    ---- def __str__(self):
    --------return self._data
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1342 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 61ms · UTC 23:48 · PVG 07:48 · LAX 16:48 · JFK 19:48
    ♥ Do have faith in what you're doing.