Class Methods, Static Methods, & Instance Methods EXPLAINED in Python

Поделиться
HTML-код
  • Опубликовано: 27 дек 2024

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

  • @JoshuaMock231
    @JoshuaMock231 2 года назад +25

    I have been learning so much from your videos! Your presentation of the material is superb. Keep up the great work!

  • @bshah276
    @bshah276 11 месяцев назад +4

    It took ages for me to understand this. I never came across with such clear explanation. Thank you. Thank you so much.

  • @mmclean0
    @mmclean0 10 месяцев назад +7

    I think you would have been better served by introducing the idea of scope in this discussion. Also, I always think the best way to introduce the topic of the class method is by introducing a class variable like an instance counter that increments/decrements when a new instance of the class is created. Also, it wouldn’t hurt to put print statements in your constructors just to illustrate when they are called and how they affect class vars.

  • @marckiezeender
    @marckiezeender 2 года назад +44

    the @staticmethod is NOT optional. Simply removing the self keyword does NOT make it a static method, and will have weird results.

    • @Indently
      @Indently  2 года назад +21

      Correct, what I said regarding that was a mistake on my part in the video.

    • @wartem
      @wartem 2 года назад +1

      Thanks

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

      @staticmethod is optional. always like that in Python. proof just run this snippet below it works fine. please dont confuse the content creator by making misleading statement as this Indently's gentleman making this content who I admire is still apparently learning Python too maybe he just read python doc once and then decided making Python videos. it needs to come from experiences. I stand corrected that the use of staticmethod decorator is OPTIONAL. All come with good intentions. hope this helps. The example code to prove it below:
      class Calculator:
      def __init__(self, version: int) -> None:
      self.version = version
      def no_static_decorator(text: str, *lucky_no: int) -> None:
      print(f'{text} and the luck number is {sum(lucky_no)}')

      Calculator.no_static_decorator("it works", 4, 9)

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

      Hej ​@@tomjones8293, actually @staticmethod is NOT optional. Static methods van be called through class name as you did. But they can be called through instance too. Try that and you'll see that without decorator Python tries to pass instance reference as a first parametr.

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

      ​@@Indently oh, can you pin that comment then?

  • @Richard-yz2gy
    @Richard-yz2gy 10 месяцев назад +1

    everytime I watch one of your videos they are always explained really well, thanks I appreciate it a lot

  • @penguinmonk7661
    @penguinmonk7661 14 дней назад

    Thank you for wearing the Christmas hat. It happens to be Christmas time again when I need this knowledge and I dunno, it just made the vid more homely, more timed and more enjoyable, thank you

  • @MonMon-ed6uw
    @MonMon-ed6uw Месяц назад

    this explaination is just the best! thank you!

  • @whkoh7619
    @whkoh7619 2 года назад +2

    Great content again. Really helpful for getting to grips with OOP in python

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

    Please don't stop making these. These videos are very useful and really enjoyable to watch!

  • @BrianStDenis-pj1tq
    @BrianStDenis-pj1tq 2 года назад +7

    You could have added that... class methods can refer to and modify class variables. These variables are shared between the class and all instances of the class. Also, static methods... you showed can be used relative to the class - as in classname.static_method(). But, you can also use them relative to an instance of the class - as in federico.age_from_year().

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

      modifying a class attribute is kinda weird...expect maybe a counter or something like that.

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

    Thank you so much for clearly explaining the difference between @classmethod and @staticmethod with an example.
    This really helped me to understand the usage of @classmethod.

  • @saltized593
    @saltized593 2 года назад

    Your thumbnail stands out so much, keep up your style man!

  • @benjaminreyes8115
    @benjaminreyes8115 2 года назад

    Interessantissimo video Federico, sono principiante nel mondo della programmazione, quindi i tuoi video hanno reso più facile la comprensione di molti concetti, continua così!

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

    great video! I'm new to coding and have just begun learning Python. I'm currently using VSCode. Which editor are you using? It looks clean with only your code and the terminal visible.

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

      PyCharm Community Edition

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

    What font are you using? I like that '->' looks like an arrow without a break

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

      Pycharm, with the setting that does that enabled

  • @geolmsu5934
    @geolmsu5934 5 месяцев назад

    Спасибо большое, стало гораздо понятнее! Thanks a lot, now i understand it much more fully. It really helpful!

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

    Awesome video! Thank you. I have never thought of it but is this the only way to override a constructor in python?

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

    if i have a python class of 1000 dogs and it all works as a class should, how do i search the dog class using a 'string' for a particular dog- say 'beagle' - I want to use a string because I am iterating through a large python list(which is strings) I can't figure out how to do it?

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

      ibreed in self.dogs
      self.dogs.index(breed)
      I'd do:
      def __iter__(self):
      for breed in self.dogs:
      yield breed
      def __ contains__(self, breed):
      return breed in list(self)
      actually, if it's a list, I'd subclass list:
      class DogList(list):
      ...
      thought py3 has a new library that helps with this, though I haven't used it, and I forgot the protocol..but never be afraid to subclass builtins.

  • @supritobiswas
    @supritobiswas 2 года назад

    Great stuff. Hardly any tutorial explains these.

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

    awesomely explained. well done

  • @danaronson4965
    @danaronson4965 2 года назад +1

    First of all I really appreciate your content.
    You are doing a great job.
    Regarding class methods and using it for constructing class instances, I'd rather use just static methods.
    Class methods are usually used for meta programing which is a way more advanced topic (which you rarely actually use)

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

    Thank you so much, finally I got the concept!

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

    This clears up these concepts!

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

    Thanks you made it really clear about the class method

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

    Thanks, that's a nice guide! I wonder what editor you are using in the video, with what extensions?

  • @dbottesi
    @dbottesi 10 месяцев назад

    Thumbs up! great video thanks

  • @sneezy_hd8362
    @sneezy_hd8362 2 года назад +4

    Is that PyCharm? Because mine looks different
    Edit: Its in the settings its called New UI

  • @KumR
    @KumR 5 месяцев назад

    Thanks. I noticed that you keep adding data types in variables as well as method return...is that really needed?

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

    @4:08, I don't think so it will be perfectly fine unless we give a static method decorator for that.

  • @mathewchan503
    @mathewchan503 2 года назад

    very clear, easy to understand

  • @khandoor7228
    @khandoor7228 2 года назад

    Great explanation!!

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

    Do static methods always have to be inside a class?

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

    I hope not to be wrong but there is a small error
    You said the addition of @staticmethod was a choice. If you remove self tho, it's not a choice anymore
    This is because python automatically sends the self argument when the function is called (in that case self will end up between the numbers) so the decorator is needed
    I'm not trying to be rude and I'm not sure I am right, so correct me if I am not

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

      You're not wrong, I made a mistake when I was recording as pointed out from several comments :)

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

      def method(*args):
      would work in either case.

  • @Bulbasauros
    @Bulbasauros 29 дней назад

    Had to overclock my brain after 6:30

  • @castlecodersltd
    @castlecodersltd 2 года назад

    Great explanation. Thank you ☺

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

    Finally, the issue I come across I believe

  • @SACHINKUMAR-px8kq
    @SACHINKUMAR-px8kq Год назад

    Thankyou so much sir

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

    can we access static method by using object reference?

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

      Yes you can but can't access the instance property (variable) so it's similar to using the normal function

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

    thank u.. but i wanna know the name of this ide that ur using

  • @حمدالسليمان-ع8ث
    @حمدالسليمان-ع8ث Год назад

    good keep it up

  • @play_itover
    @play_itover 2 года назад

    Hey listen I want a brief lecture on class and class function

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

      a class is a dictionary of variables and functions. There are no class functions. It's class method, instance method, static method.

  • @Naruto.Hinata-clips
    @Naruto.Hinata-clips Год назад

    Good

  • @Rizz_The_One
    @Rizz_The_One 2 года назад

    I like ur performance :) # thumb up

  • @rewazzu
    @rewazzu 2 года назад +1

    Good video

  • @duopleis
    @duopleis 10 месяцев назад

    sublime

  • @fairphoneuser9009
    @fairphoneuser9009 2 года назад

    Actually WTF is the answer! OOP in Python is a mess!

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

      why?

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

      @@DrDeuteron Just look at it. It's all implemented really weirdly. I don't know a single language that has as weird OOP as Python...

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

      @@fairphoneuser9009 I think it makes perfect sense. Do you ever call super or use meta classes?

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

    One tiny unrelated fix - Your "age_from_year" function actually needs the exact date of birth, to determine your age, so it can check whether current date is before or after your birthday. If you only enter 1997, and now we are in 2023, running your code today returns an age of 26, but if your birthday is in August, and today we're in February, you are still 25.

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

      ok but this is demo code, to show static - class difference, the real code would also react to leap year.

  • @aryansinha1818
    @aryansinha1818 7 месяцев назад

    Note: see that __main part

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

    Nide

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

    I use classmethods all the time, esp. as constructor helpers...since I never do work in __init__, that method is for setting instance attributes, and that is it. If I need to, say make the instance from a file...I am not reading a file in init, rather:
    @classmethod
    def fromfile(cls, filename):
    with open(filename, 'r') as fsrc:
    return cls(*some_function(fsrc.readlines())
    and I get a new instance with the file data loaded.
    For static methods, say I have a class whose attributes are different real time series, well if I want an fft or something:
    @staticmethod
    def rfft(x_i):
    return np.fft.rfff(x_i)
    the reason I put it in class is that I want the object to be able to do everything that needs to be done to it to be part of the interface. I don't want a user looking for np.ftt.rftt and doing it themselves, or making the mistake of using a full fft for complex inputs. A class should contain ALL the functions you would want to use on it,,,even if they don't depend on instance/class attributes.