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

แชร์
ฝัง
  • เผยแพร่เมื่อ 28 ก.ย. 2024
  • 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

ความคิดเห็น • 63

  • @DerBarde2012
    @DerBarde2012 7 หลายเดือนก่อน +1

    Thanks, this will allow checking values before writing them

  • @ordinaryBrain4300
    @ordinaryBrain4300 3 หลายเดือนก่อน +4

    This was the most easy tutorial for me to understand this super confusing thing. Thanks!

  • @dalkap
    @dalkap ปีที่แล้ว +44

    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 ปีที่แล้ว +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 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

  • @lisav9566
    @lisav9566 7 หลายเดือนก่อน +1

    Thanks, you help me much for work and studies :)

  • @aventurileluipetre
    @aventurileluipetre 5 หลายเดือนก่อน +2

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

  • @techiehkr5352
    @techiehkr5352 2 ปีที่แล้ว +28

    __name #private
    _name #protect
    name #public

    • @darthrochon
      @darthrochon ปีที่แล้ว +8

      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 ปีที่แล้ว +5

      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 ปีที่แล้ว +2

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

  • @mihaiciorobitca4949
    @mihaiciorobitca4949 5 หลายเดือนก่อน

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

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

  • @Shao-LunHuang
    @Shao-LunHuang ปีที่แล้ว +6

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

  • @AbhishekVaid
    @AbhishekVaid 6 หลายเดือนก่อน +1

    This is still so verbose for something so simple

  • @ordinaryBrain4300
    @ordinaryBrain4300 3 หลายเดือนก่อน +1

    People he made this tutorial because it's a valid Python thing and its confusing. This is for those who wants to understand it. For example, I'm just following a curriculum that has this decorator in it. So this was useful to me. Stop hating.

  • @_KobbyOb
    @_KobbyOb ปีที่แล้ว +12

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

    • @Indently
      @Indently  ปีที่แล้ว +3

      You're right, I messed up in the video

    • @wrichik_basu
      @wrichik_basu ปีที่แล้ว +10

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

  • @ganzaian430
    @ganzaian430 10 หลายเดือนก่อน +2

    Big Man Ting , this is actually great stuff and simple

  • @jasmeet2365
    @jasmeet2365 ปีที่แล้ว +2

    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

  • @LEGENDKINETIC
    @LEGENDKINETIC 5 หลายเดือนก่อน +1

    Awesome dude. I finally understood it. 🎉

  • @TheDiveO
    @TheDiveO ปีที่แล้ว

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

  • @iHaAcKs
    @iHaAcKs 2 ปีที่แล้ว +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.

    • @TobiasFors-w5l
      @TobiasFors-w5l 11 หลายเดือนก่อน

      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

    • @victorsago
      @victorsago 13 วันที่ผ่านมา

      You're not mapping one variable to another -- you're mapping an instance attribute to functionality. This way, you can validate any assignments to this property. You can also protect your instance attribute by not creating a setter.
      This video isn't such a good explanation of this feature.

  • @tenminutetokyo2643
    @tenminutetokyo2643 2 ปีที่แล้ว +2

    That’s nuts!

    • @orangmakan
      @orangmakan 10 หลายเดือนก่อน +1

      No, its bananas.

  • @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?

  • @michel2409
    @michel2409 7 หลายเดือนก่อน

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

  • @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 11 หลายเดือนก่อน

      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.

  • @lovemesy3731
    @lovemesy3731 ปีที่แล้ว

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

  • @shabareesha1217
    @shabareesha1217 ปีที่แล้ว

    thanks

  • @Boljedorus
    @Boljedorus ปีที่แล้ว

    Спасибо !

  • @evilservo
    @evilservo 7 หลายเดือนก่อน

    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 6 หลายเดือนก่อน

      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

  • @the_wizard_exe
    @the_wizard_exe 8 หลายเดือนก่อน +7

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

  • @kamurashev
    @kamurashev ปีที่แล้ว +7

    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 ปีที่แล้ว +3

      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 ปีที่แล้ว

    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.

  • @wristocrat
    @wristocrat ปีที่แล้ว +1

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

    • @Indently
      @Indently  ปีที่แล้ว +3

      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 ปีที่แล้ว

      @@devnull1013 you definitely have no idea what you're talking about. The video is not really about calling methods for accessing values.