English 中文(简体)
如何在一项职能中使用当地变量并回报?
原标题:How to use local variable in a function and return it?

我正试图制作一个文字,列出地方变量,将其从功能中引出,并将操纵价值退回到主要范围(或无论它所呼吁的是什么;我是新到沙里)。

我认为,我已经简化了我的法典,以显示我努力完成的工作的最基本条件,即从单元进口一个地方,成为功能区。

我通过使用<条码>Globals,而这是最佳解决办法。

chambersinreactor = 0;
cardsdiscarded = 0;

def find_chamber_discard(): 
    """Find chambers and discard in row (reads each player slot)"""
    chambersinreactor = 0; # Resets the variable, not what I want
    cardsdiscarded = 0; # Resets the variable, not what I want
    chambersinreactor += 1
    cardsdiscarded += 1
    return # Don t know what to put here

find_chamber_discard()

print chambersinreactor # prints as 0, should be 1
print cardsdiscarded    # prints as 0, should be 1
问题回答

职能不一定要知道它们要求什么范围;职能点是使可重新使用的守则成为不同地点多次援引的系统。

You communicate information to a function by passing it through its input variables. The function communicates information back to its caller by returning it.

管理范围的各种变量是该守则在该范围中的工作而不是它援引的任何职能。 如果你需要根据一项职能确定的价值确定变数,那么你就能够恢复这些价值,并使用这些数值确定变数。 如果该功能的计算值取决于你在呼吁范围中具有的变量的数值,那么,你需要将这些数值作为理由予以通过。 你再次要求你履行的职能是,必须知道你重新使用哪些变量,并且不能与这些变量做我。

你们想要做的事情就是这样:

def find_chamber_discard(chambersinreactor, cardsdiscarded):
    chambersinreactor += 1
    cardsdiscarded += 1
    return (chambersinreactor, cardsdiscarded)

chambersinreactor = 0;
cardsdiscarded = 0;

chambersinreactor, cardsdiscarded = find_chamber_discard(chambersinreactor, cardsdiscarded)

print chambersinreactor
print cardsdiscarded

有办法利用全球变数或操纵变数数据结构来解决这一问题,但最终使你的方案不那么灵活,更有可能控制难以发现的错误。 有了这些技术的地方,但你向实际职能传递信息的第一个方法应该是通过论点和接受回报价值。

One approach is to use mutable values, like dicts or lists:

settings = dict(
    chambersinreactor = 0,
    cardsdiscarded = 0
)

def find_chamber_discard():
    settings[ chambersinreactor ] += 1
    settings[ cardsdiscarded ] += 1

find_chamber_discard()

print settings[ chambersinreactor ]
print settings[ cardsdiscarded ]

然而,如果你的职能正在改变某些状态,那么你也许会比平整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整,

class CardCounter(object):
    def __init__(self):
        chambersinreactor = 0
        cardsdiscarded = 0

    def find_chamber_discard(self, hand):
        for card in hand:
            if card.is_chamber:
                self.chambersinreactor += 1
            if card.is_discarded:
                self.cardsdiscarded += 1

如果你重新计算,也许你可以采取反响:

from collections import Counter

def test_for_chamberness(x): return x ==  C 
def test_for_discarded(x): return x ==  D 

def chamber_or_discard(card):
    if test_for_chamberness(card):
        return  chambersinreactor 
    if test_for_discarded(card):
        return  cardsdiscarded 

hand = [ C , C , D , X , D , E , C ]

print Counter(
    x for x in (chamber_or_discard(card) for card in hand) if x is not None
)

从个人角度讲,我倾向于采取班级办法,甚至总结反响,因为它把所有相关功能放在一起。

#!/usr/bin/env python
chambersinreactor = 0; cardsdiscarded = 0;

def find_chamber_discard():
    chambersinreactor = 0
    cardsdiscarded = 0
    chambersinreactor += 1 
    cardsdiscarded += 1 
    return(chambersinreactor, cardsdiscarded)

#Here the globals remain unchanged by the locals.
#In python, a scope is similar to a  namespace 
find_chamber_discard()

print chambersinreactor #prints as 0
print cardsdiscarded 

#I ve modified the function to return a pair (tuple) of numbers.
#Above I ignored them. Now I m going to assign the variables in the 
#main name space to the result of the function call.
print("=====with assignment===")
(chambersinreactor, cardsdiscarded) = find_chamber_discard()

print chambersinreactor #  now prints as 1
print cardsdiscarded 

# Here is another way that doesn t depend on returning values.
#Pass a dictionary of all the main variables into your function
#and directly access them from within the function as needed

print("=======using locals===")
def find_chamber_discard2(_locals):
    _locals[ chambersinreactor ] += 1
    _locals[ cardsdiscarded ] += 1
    return

find_chamber_discard2(locals())

print chambersinreactor #incremented the value, which was already 1
print cardsdiscarded 




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签