THIS Is How You Should Be Making Getters & Setters In Python

  Рет қаралды 53,174

Indently

Indently

Жыл бұрын

This is how you should be making getters & setters in Python. It's simple and doesn't require any change to existing variable names. In the example I changed "_name" to "fruit_name", but you don't have to do that, you can easily just call it "name".
▶ Become job-ready with Python:
www.indently.io
▶ Follow me on Instagram:
/ indentlyreels

Пікірлер: 62
@ganzaian430
@ganzaian430 6 ай бұрын
Big Man Ting , this is actually great stuff and simple
@LEGENDKINETIC
@LEGENDKINETIC Ай бұрын
Awesome dude. I finally understood it. 🎉
@DerBarde2012
@DerBarde2012 3 ай бұрын
Thanks, this will allow checking values before writing them
@lisav9566
@lisav9566 3 ай бұрын
Thanks, you help me much for work and studies :)
@user-uu2yg9cx6u
@user-uu2yg9cx6u 9 ай бұрын
Amazing Explanation
@Shao-LunHuang
@Shao-LunHuang Жыл бұрын
The only circumstance that I think can make the setter and getter useful is to add additional functionality like checking the validity of the input. Yet, I do not know whether this is a good practice :/
@lovemesy3731
@lovemesy3731 8 ай бұрын
thank you so much i was so confused before i saw your video
@iHaAcKs
@iHaAcKs Жыл бұрын
What is the advantage of this property wrappers compared to use the class variable directly? At the beginning you talk about private variables. But the variable "_name" is still not private with these property wrappers, right? Currently, it feels like #pragma in C to map one variable to another and I don't really see the advantage. It adds way more code compared to use the class variable directly. Am I missing something?
@harrison1508
@harrison1508 Жыл бұрын
I was curious about this myself and there’s no advantage to using this method if all you are doing is truly getting/setting/deleting etc… in fact you can see that it’s actually even more lines of code to implement the property. The reason you might actually use this in real life situation is if you wanted additional functionality on accessing/deleting/setting the variable such as validations, logging or printing, or really anything else that isn’t natively handled by just accessing the variable directly. All that to say I’ve never used properties because I feel like there’s no need to but there are probably some valid use cases
@GooogleGoglee
@GooogleGoglee Жыл бұрын
All you have seen is based on an attempt of a standardization and best practices but it is not a default feature of Python. It is a good common programming practice!
@BrunoBeltran
@BrunoBeltran Жыл бұрын
You should use the class variable directly if it's available and equally easy. You should also avoid getters that contain any code that might take a long time to run (serious computation, network or disk access, etc). If you find that you want to add more code to your gretter and setter but none currently exist, only then is this useful.
@user-pu4nv5cw2v
@user-pu4nv5cw2v 7 ай бұрын
There are two reasons we use properties, mostly. 1. It makes backwards compatability easier, since we can change the output of an already referenced attribute or ensure that future implementations might change for this particular value 2. We can implement checks for operations I would avoid properties for a non public attribute and instead use methods (we don't say private in python) if you perform any sort of demanding calculation or side effect that takes time. Basically, properties should always behave similar in terms of speed to accessing a data attribute. @@harrison1508
@the_wizard_exe
@the_wizard_exe 4 ай бұрын
there's as 400 long page articles and this pro achieved to explain it into seven minutes
@michel2409
@michel2409 3 ай бұрын
Very good, but, can you enlarge the screen?😊
@tenminutetokyo2643
@tenminutetokyo2643 Жыл бұрын
That’s nuts!
@orangmakan
@orangmakan 6 ай бұрын
No, its bananas.
@Davidozz76
@Davidozz76 Жыл бұрын
Why not declare fruit name as private using the double underscore trick? class Fruit: def __init__(self, name): self.__name = name @property def name(self): return self.__name @name.setter def name(self, new_name): if type(new_name) == str: self.__name = new_name else: print("New name must be a string!") fruit = Fruit("banana") print(fruit.name) fruit.name = 45 # here an error occurs fruit.name = "orange" print(fruit.name) OUTPUT: banana New name must be a string! orange
@vijaykumarchauhan1692
@vijaykumarchauhan1692 Жыл бұрын
same error
@alexd7466
@alexd7466 Жыл бұрын
double underscore is for name mangling (to avoid name collisions resulting from inheritance), and since you are not inheriting anything here, that would not make any sense.
@wrichik_basu
@wrichik_basu Жыл бұрын
@Davidozz76 Exactly!
@QuintinMassey
@QuintinMassey 7 ай бұрын
Though I don’t think double underscore is needed in your example because you’re not inheriting anything, I would instead use the single underscore with your naming condition.
@aventurileluipetre
@aventurileluipetre Ай бұрын
This is longer.... Why would I do that
@Boljedorus
@Boljedorus 8 ай бұрын
Спасибо !
@jasmeet2365
@jasmeet2365 Жыл бұрын
Can't we just use "__get__" and "__set__" dunder method for implementing getters and setters in a class. Can someone explain ?
@gabi_kun3455
@gabi_kun3455 Жыл бұрын
I guess it is because the @property class-decorator already has his own system: his "__init__", his attributes, his methods, and of course his "__set__", his "__get__" and his "__delete__", with @property you can create a setters, getters and deleters easily but you cannot change those things, to do that you need to create a new class with those dunder methods
@_KobbyOb
@_KobbyOb Жыл бұрын
I thought declaring an attribute with an underscore makes it protected rather than private.
@Indently
@Indently Жыл бұрын
You're right, I messed up in the video
@wrichik_basu
@wrichik_basu Жыл бұрын
@@Indently You should post a pinned comment rectifying your mistake. We all make mistakes; it's important to rectify it. ;-)
@dalkap
@dalkap Жыл бұрын
Honestly that just seems longer and less readable to me, but if there's a good reason to use it I'm happy to be proven wrong!
@BrunoBeltran
@BrunoBeltran Жыл бұрын
You should use the class variable directly if it's available and equally easy. You should also avoid getters that contain any code that might take a long time to run (serious computation, network or disk access, etc). If you find that you want to add more code to your getter and setter but none currently exist, only then is this useful, since you can then migrate to this approach and users of your class won't need to change their code.
@dalkap
@dalkap Жыл бұрын
@@BrunoBeltran Yeah but what's good about using this rather than the usual get/set? As I said, it's just less readable to my eyes, but maybe I misunderstood something you said
@BrunoBeltran
@BrunoBeltran Жыл бұрын
@@dalkapin short: backyard compatibility. I will assume you don't mean that `obj.name` is less readable to you than `obj.get_name()`, since that would be hard to imagine. The difference between the implementation of the python getter vs the equivalent method with the `get_` prefix is arguably a small price to pay for the benefit of not having to type get, but that's not even the main benefit. The flexibility of being able to expose a class member as public attribute and still retain the ability to change its implementation later while not breaking backwards compatibility is a huge win. As a language feature, properties of classes encourage transparency in Python class implementations that's hard to find elsewhere.
@JasonYokoyama
@JasonYokoyama Жыл бұрын
​@dalkap setting normalized types is a pretty common reason. Set a string, int, etc and have the underlying to your native type.
@sandokan888
@sandokan888 Жыл бұрын
this is not fkin java I see no reason to do this in python
@shabareesha1217
@shabareesha1217 8 ай бұрын
thanks
@mihaiciorobitca4949
@mihaiciorobitca4949 Ай бұрын
namin' attribute startin' with 2 _ will make it private it is my observation
@evilservo
@evilservo 3 ай бұрын
This is really confusing i mean why we need a setter when we can access a private property outside a class I mean simply fruit.fruit_name = '''orange ' will change the name what is the point of setters and getters
@eitantal726
@eitantal726 2 ай бұрын
that's the difference between a data structure and a class. Class has logic, data structure is entirely freeform. For example, a class representing a graphics block. You want the pixels having R&W access, but you also want to refresh your block upon write
@Etk333
@Etk333 Жыл бұрын
Seems like this method is old school and using it kind of downplays on the advantages of python. Regardless everyone says it's a good concept so I'll practice it I suppose?
@techiehkr5352
@techiehkr5352 Жыл бұрын
__name #private _name #protect name #public
@darthrochon
@darthrochon Жыл бұрын
what's the point since they actually are all public anyway
@techiehkr5352
@techiehkr5352 Жыл бұрын
@@darthrochon it matters when we want to access variable inside function
@GooogleGoglee
@GooogleGoglee Жыл бұрын
@@darthrochon it is a convention and a good smart programming best practice. You can make your programs without it but probably no one will spend much effort to help you out in case of problems... It is an attempt of standardization.
@alexd7466
@alexd7466 Жыл бұрын
that is wrong. Read the Python manual, it explicitly mentions that there is no 'private' in python. double underscore is for name-mangling (to prevent name clashes), not for hiding stuff.
@sauloaccaio
@sauloaccaio Жыл бұрын
just more complex and u must write more code.... but tk for informtion
@horuscoming
@horuscoming Жыл бұрын
How would this make me not having to refactor the code in long run? If I was to write this for every property I have, I would have to write 3 instead of 2 lines(in case of normal setters and getters). So no, your arguments are invalid.
@Indently
@Indently Жыл бұрын
My arguments are backed by the official Python docs, you don't have to agree with me or them, and you are more than free to have your own free opinion :)
@TheDiveO
@TheDiveO Жыл бұрын
This literally popped up after Michael Spencer's parody on literally. Another victim here to watch.
@kamurashev
@kamurashev Жыл бұрын
And they say Java is bad 🫣🤯
@Indently
@Indently Жыл бұрын
It is
@kamurashev
@kamurashev Жыл бұрын
@@Indently from the person who never know it perspective? Sure.
@adolfomartin5456
@adolfomartin5456 Жыл бұрын
ja ja ja it's true. I cannot justify python on this, which is horrible.
@AbhishekVaid
@AbhishekVaid 2 ай бұрын
This is still so verbose for something so simple
@AKHILDABRAL
@AKHILDABRAL 10 ай бұрын
This all can be done using one line @Getter and @Setter annotations in Java don't know why Guido has to make it this stupid. How difficult it could be to implement static typing , even type hinting is all about bullshitting same as name mangling. Mojo have to create another language just to fixed these little much necessary functionality.
@hooverzavala4560
@hooverzavala4560 Жыл бұрын
1:11 use _ to make protected; use __ to make private, wasting time...
@wristocrat
@wristocrat Жыл бұрын
dont see any practical difference and just makes it harder to read. fake news. wack
@Indently
@Indently Жыл бұрын
Do you just type fake news at everything you don't understand?
@devnull1013
@devnull1013 11 ай бұрын
Ah yes, having "v = c.get_x()" and "c.set_x(v) all over your code base is much easier to read than "v = c.x" and "c.x = v" for sure. /s
@MFM88832
@MFM88832 10 ай бұрын
@@devnull1013 you definitely have no idea what you're talking about. The video is not really about calling methods for accessing values.
Cat story: from hate to love! 😻 #cat #cute #kitten
00:40
Stocat
Рет қаралды 14 МЛН
Как быстро замутить ЭлектроСамокат
00:59
ЖЕЛЕЗНЫЙ КОРОЛЬ
Рет қаралды 9 МЛН
AI for Embedded Systems | Embedded systems podcast, in Pyjama
25:32
Embedded Systems, in Pyjama!
Рет қаралды 33
HOW TO USE DECORATORS IN PYTHON 2022 (THE RIGHT WAY)
6:42
Indently
Рет қаралды 51 М.
5 More Useful F-String Tricks In Python
9:38
Indently
Рет қаралды 39 М.
PLEASE Use These 5 Python Decorators
20:12
Tech With Tim
Рет қаралды 89 М.
Python JSON Mastery: From Strings to Services
13:36
The Code Guy
Рет қаралды 443
6/6 OOP & Classes in Python: Properties, Getter, Setter and Deleter | Attribute Validation and More
13:48
Python: A Quick Guide To Type Annotations (ft. Mypy)
11:25
Indently
Рет қаралды 25 М.
5 Useful Python Decorators (ft. Carberra)
14:34
Indently
Рет қаралды 83 М.
5 Useful Dunder Methods In Python
16:10
Indently
Рет қаралды 49 М.
Python dataclasses will save you HOURS, also featuring attrs
8:50
Cat story: from hate to love! 😻 #cat #cute #kitten
00:40
Stocat
Рет қаралды 14 МЛН