0

I want to check if my global variable item got rewrite with the value of my function copy()

I do not know how does scope works

The problem here is that, when a class register() is called, and the instance is done with proof, the value is [0] again, which is not my goal. I want to re-write it with de value of de inner function

class register():
    item = [0]
    print(f'item before function -> {item} <id> = {id(item)}')
    def __init__(self, quantity = '20', fabric_c = 'client', fabric_p = 'own'):
        self.quantity = quantity
        self.fabric_c = fabric_c
        p_c = True
     def copy(self):
        if p_c == True:
            line = self.quantity + ' meters ' + self.fabric_c
            item = line
            print(f'printing description during execution function -> {line} <id> = {id(item)})')
        return item
        print(f'item after function -> {item} <id> = {id(item)}')
proof = register()
proof.copy()

print(f'proof.item = {proof.item} outside of class -> {id(proof.item)}')

# [out] : item before function -> [0] <id> = 140627839165312

# [out] : printing description during execution function -> 20 meters client <id> = 140627839182128)

# [out] : proof.item = [0] outside of class -> 140627839165312

And also as you can see, the id value of item in the inner function ,is no the same as the value of the global variable item

  • 2
    In `copy` you assign to a global variable called `item`, not to the class attribute `register.item`. – khelwood May 17 '21 at 04:06
  • 1
    And by the way, the output of this program is not what you say it is. The `item_after_function` print shows `[0]` because it happens during the class definition. Perhaps you messed up it's indentation when you posted it. Also `p_c` is undefined in the `copy` method. – khelwood May 17 '21 at 04:12

1 Answers1

0

The item at the top of class register is not global. It's a class attribute. The item inside copy is global (actually a module attribute). The proof.item at the bottom resolves to the class attribute. The global at that point would be simply item.

luther
  • 5,195
  • 1
  • 14
  • 24