As the title says.
Coming from Java im used to:
private int A;
public void setA(int A) {
this.A = A;
}
public int getA() {
return this.A
}
How do I do that (if I need to) in Python.
And if one of __setattr__ or __set__ is used for this, what is the other one used for?
Edit:
I feel I need to clarify. I know that in Python one doe’s not create setters and getters before they are needed.
Lets say I want to do something like this:
public void setA(int A) {
update_stuff(A);
and_calculate_some_thing(A);
this.A = A;
}
What is the “pythonic” way to implement this?
In python, something like this should be implemented using a
property(and then only when they do something useful).In this example, it would be better to just do (as pointed out by Edward):
since our getter/setter methods don’t actually do anything … However, properties become very useful when the setter/getter actually does something more than just assign/return an attribute’s value.
It could also be implemented using
__setattr__/__getattr__(but it shouldn’t be implemented this way as it quickly becomes cumbersome if your class has more than 1 property. I would also guess that doing it this way would be slower than using properties):In terms of what
__setattr__and__getattr__actually do…__setattr__/__getattr__are what are called when you do something like:As for
__get__and__set__: previous posts have discussed that quite nicely.Note that in python there is no such thing as private variables. In general, in a class member is prefixed with an underscore, you shouldn’t mess with it (unless you know what you’re doing of course). If it’s prefixed with 2 underscores, it will invoke name-mangling which makes it harder to access outside the class. This is used to prevent namespace clashes in inheritance (and those variables are generally also not to be messed with).