0

How can I pass class attribute to a class method so that the attribute will be modified?


class foo:
    def __init__(self):
        self.diamond = 1
        self.gold = 10
        self.change(self.diamond)
        self.change(self.gold)
    def change(self, x):
        x+=1
model = foo()
print(model.diamond)

output: 1

I want diamond becomes 2.

2 Answers 2

1

Is this a good solution for you?

class foo:
    def __init__(self):
        self.diamond = 1

    def change(self):
        self.diamond += 1

model = foo()
model.change()
print(model.diamond)
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry for the misleading. I edited my question. I want to write a general method change so that every attribute can use this method to get increasement.
0

Let me say this first that you have no class method, or class variable in your example. What you have are instance variables and instance methods, note the self keyword. Now, with that said, you can access and modify your instance variables from any instance method, just like @Almog answered earlier.

The x in your change method is a local variable, basically it's not available outside your method. As for how you modify a variable by passing it to a function, it's not doable with your code I think. You would need something like a dataclass, which you can modify. Check out 'PassByValue' and 'PassByReference' concepts relating to this. Maybe someone else here can help with your particular situation.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.