Molin.L
Molin.L

Reputation: 113

Pass attribute to class method

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.

Upvotes: 0

Views: 147

Answers (2)

Harsh
Harsh

Reputation: 405

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.

Upvotes: 0

Almog
Almog

Reputation: 448

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)

Upvotes: 1

Related Questions