How to use local variable in a function and return it?

前端 未结 3 1200
囚心锁ツ
囚心锁ツ 2020-12-15 12:54

I am trying to create a script that sets a local variable, references it from a function, and can return the manipulated value back to the main scope (or whatever it\'s call

3条回答
  •  忘掉有多难
    2020-12-15 13:07

    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']
    

    However, if you have a function that is changing some state, you're probably better off wrapping that all up in class, as that's what they're for:

    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
    

    If what you're doing is counting, maybe you could use Counter:

    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
    )
    

    Personally, I'd go for the class approach, perhaps even wrapping Counter, as it keeps all the associated functionality together.

提交回复
热议问题