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

Поделиться
HTML-код
  • Опубликовано: 17 сен 2022
  • 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

Комментарии • 60

  • @ganzaian430
    @ganzaian430 6 месяцев назад +1

    Big Man Ting , this is actually great stuff and simple

  • @LEGENDKINETIC
    @LEGENDKINETIC Месяц назад +1

    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 :)

  • @lovemesy3731
    @lovemesy3731 8 месяцев назад

    thank you so much i was so confused before i saw your video

  • @Shao-LunHuang
    @Shao-LunHuang Год назад +3

    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 :/

  • @the_wizard_exe
    @the_wizard_exe 4 месяца назад +6

    there's as 400 long page articles and this pro achieved to explain it into seven minutes

  • @iHaAcKs
    @iHaAcKs Год назад +21

    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?

    • @GooogleGoglee
      @GooogleGoglee Год назад +7

      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 Год назад +3

      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 8 месяцев назад

      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

  • @tenminutetokyo2643
    @tenminutetokyo2643 Год назад +2

    That’s nuts!

    • @orangmakan
      @orangmakan 6 месяцев назад

      No, its bananas.

  • @dalkap
    @dalkap Год назад +42

    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 Год назад +1

      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 Год назад +1

      this is not fkin java I see no reason to do this in python

  • @aventurileluipetre
    @aventurileluipetre 2 месяца назад +2

    This is longer.... Why would I do that

  • @Boljedorus
    @Boljedorus 8 месяцев назад

    Спасибо !

  • @shabareesha1217
    @shabareesha1217 9 месяцев назад

    thanks

  • @jasmeet2365
    @jasmeet2365 Год назад +1

    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 Год назад +11

    I thought declaring an attribute with an underscore makes it protected rather than private.

    • @Indently
      @Indently  Год назад +2

      You're right, I messed up in the video

    • @wrichik_basu
      @wrichik_basu Год назад +9

      @@Indently You should post a pinned comment rectifying your mistake. We all make mistakes; it's important to rectify it. ;-)

  • @Davidozz76
    @Davidozz76 Год назад +25

    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 Год назад +10

      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.

  • @michel2409
    @michel2409 3 месяца назад

    Very good, but, can you enlarge the screen?😊

  • @mihaiciorobitca4949
    @mihaiciorobitca4949 Месяц назад

    namin' attribute startin' with 2 _ will make it private it is my observation

  • @evilservo
    @evilservo 4 месяца назад

    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 3 месяца назад

      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

  • @techiehkr5352
    @techiehkr5352 Год назад +27

    __name #private
    _name #protect
    name #public

    • @darthrochon
      @darthrochon Год назад +6

      what's the point since they actually are all public anyway

    • @techiehkr5352
      @techiehkr5352 Год назад +2

      @@darthrochon it matters when we want to access variable inside function

    • @GooogleGoglee
      @GooogleGoglee Год назад +7

      @@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 Год назад +3

      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.

  • @Etk333
    @Etk333 Год назад +1

    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?

  • @sauloaccaio
    @sauloaccaio Год назад +2

    just more complex and u must write more code.... but tk for informtion

  • @TheDiveO
    @TheDiveO Год назад

    This literally popped up after Michael Spencer's parody on literally. Another victim here to watch.

  • @horuscoming
    @horuscoming Год назад +1

    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  Год назад +1

      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 :)

  • @kamurashev
    @kamurashev Год назад +5

    And they say Java is bad 🫣🤯

    • @Indently
      @Indently  Год назад +5

      It is

    • @kamurashev
      @kamurashev Год назад +3

      @@Indently from the person who never know it perspective? Sure.

    • @adolfomartin5456
      @adolfomartin5456 Год назад +1

      ja ja ja it's true. I cannot justify python on this, which is horrible.

  • @hooverzavala4560
    @hooverzavala4560 Год назад +1

    1:11 use _ to make protected; use __ to make private, wasting time...

  • @AKHILDABRAL
    @AKHILDABRAL 11 месяцев назад

    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.

  • @AbhishekVaid
    @AbhishekVaid 2 месяца назад

    This is still so verbose for something so simple

  • @wristocrat
    @wristocrat Год назад +1

    dont see any practical difference and just makes it harder to read. fake news. wack

    • @Indently
      @Indently  Год назад +2

      Do you just type fake news at everything you don't understand?

    • @devnull1013
      @devnull1013 Год назад

      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.