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
cc7756789
V2EX  ›  Python

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

  •  
  •   cc7756789 · 2015-05-24 09:36:53 +08:00 · 3463 次点击
    这是一个创建于 3268 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 条回复    2015-05-24 13:15:28 +08:00
    horizon
        1
    horizon  
       2015-05-24 09:58:57 +08:00
    self啊,你在all_answer中把想要传的值保存到self中,然后在save中使用就行了吧。
    oott123
        2
    oott123  
       2015-05-24 10:04:33 +08:00 via Android
    不应该是 a.save(each, path, pattern) 么…
    cc7756789
        3
    cc7756789  
    OP
       2015-05-24 10:31:06 +08:00
    answers = question.all_answer()
    question.save(answers, '/home/zhg/Pictures/result.txt', 'w')
    但是这种似乎不太人性化啊
    期望的效果是
    answers.save(....)
    dddd
        4
    dddd  
       2015-05-24 13:00:51 +08:00
    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  
       2015-05-24 13:15:28 +08:00
    我懂你意思了。。。。

    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
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2585 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 13:30 · PVG 21:30 · LAX 06:30 · JFK 09:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.