0

Properties

learning more classes and stuff, someone please explain properties

8th Oct 2024, 9:03 PM
podle Playz
podle Playz - avatar
4 Antworten
+ 4
Python has variables, of course. When a variable is inside a class, it's called a property. If you have a class, let's say Balloon. It has in internal variable (property), color. Each balloon instance can be a different color. Therefore, instead of calling it a class variable, they call it a class property because the value of that variable is unique to each instance of that object. An object has properties (variables) and methods (functions). An object may also have static properties and static methods as well. Static means they don't belong to the instance, but are defined within the class. But that's a different topic. :)
8th Oct 2024, 9:25 PM
Jerry Hobby
Jerry Hobby - avatar
+ 1
The setters/getters are optional. They give you a way to do additional things when someone sets and/or gets a value. Sometimes you want to validate a value. Your setter can enforce that the new value is within range, etc. Or can update other variables as well. Perhaps when someone updates "count", you also want to update another variable as well. The setter lets you gather all that into a function. Getters could also have additional functionality. Perhaps your variable needs some calculation or validation. One scenario might be that you want to make a log entry whenever someone reads a value. Think about a banking app where every time someone reads a value, you want to log that request. Or perhaps refresh that variable from another source each time that variable is accessed. Or perhaps the getter actually returns a calculated value. While you could implement that calculation as a function, you could also make your property behave like a property but have the capabilities of a function by adding a getter to it. Special code in getters is less common than special code in setters.
8th Oct 2024, 10:35 PM
Jerry Hobby
Jerry Hobby - avatar
+ 1
class Test: def __init__(self, a, b): self.__a = a self.__b = b # methods a and b are getters def a(self): return self.__a # b used the @property decorator @property def b(self): return self.__b t1 = Test(1,2) print(t1.a()) print(t1.b) # @property allows you to call the method without using '()'
9th Oct 2024, 6:44 AM
Bob_Li
Bob_Li - avatar
0
Jerry Hobby that's my fault, I forgot to put "@" before properties. I was talking about properties in OOP i believe. I don't understand the .setter, .getter and scenarios you'd need it
8th Oct 2024, 10:09 PM
podle Playz
podle Playz - avatar