The Ultimate Guide to Writing Classes in Python

  Рет қаралды 103,019

ArjanCodes

ArjanCodes

Күн бұрын

In this video, I'll share 5 essential tips for writing Python classes that will help you take your object-oriented programming skills to the next level.
Git Repo ➡️ git.arjan.codes/2023/classguide
👷 Join the FREE Code Diagnosis Workshop to help you review code more effectively using my 3-Factor Diagnosis Framework: www.arjancodes.com/diagnosis
💻 ArjanCodes Blog: www.arjancodes.com/blog
✍🏻 Take a quiz on this topic: www.learntail.com/quiz/qcitkg
🎓 Courses:
The Software Designer Mindset: www.arjancodes.com/mindset
The Software Designer Mindset Team Packages: www.arjancodes.com/sas
The Software Architect Mindset: Pre-register now! www.arjancodes.com/architect
Next Level Python: Become a Python Expert: www.arjancodes.com/next-level...
The 30-Day Design Challenge: www.arjancodes.com/30ddc
🛒 GEAR & RECOMMENDED BOOKS: kit.co/arjancodes.
👍 If you enjoyed this content, give this video a like. If you want to watch more of my upcoming videos, consider subscribing to my channel!
💬 Discord: discord.arjan.codes
🐦Twitter: / arjancodes
🌍LinkedIn: / arjancodes
🕵Facebook: / arjancodes
📱Instagram: / arjancodes
♪ Tiktok: / arjancodes
👀 Code reviewers:
- Yoriz
- Ryan Laursen
- Dale Hagglund
🎥 Video edited by Mark Bacskai: / bacskaimark
🔖 Chapters:
0:00 Intro
0:54 Keep your classes small
8:43 Make your classes easy to use
14:18 Use dependency injection
17:46 Make sure a class is actually needed
22:45 Use encapsulation
24:57 Outro
#arjancodes #softwaredesign #python
DISCLAIMER - The links in this description might be affiliate links. If you purchase a product or service through one of those links, I may receive a small commission. There is no additional charge to you. Thanks for supporting my channel so I can continue to provide you with free content each week!

Пікірлер: 159
@ArjanCodes
@ArjanCodes 7 ай бұрын
👷 Join the FREE Code Diagnosis Workshop to help you review code more effectively using my 3-Factor Diagnosis Framework: www.arjancodes.com/diagnosis
@philscosta
@philscosta Жыл бұрын
"Let's split a person in three different parts", "Let's look at the body"... Just normal software developer vocabulary...
@arrudabruno10
@arrudabruno10 8 ай бұрын
Lol
@AbdellahBilla
@AbdellahBilla Жыл бұрын
I could argue on the PhourthPhart "Make sure a class is actually needed" in your example and in my opinion, the class was much simpler, connected, and easy to scale, but with functions, you made it hard to use.
@chaz2290
@chaz2290 7 ай бұрын
Exactly what I was going to say. Although I appreciate it's difficult finding a good example in videos like this.
@sevdalink6676
@sevdalink6676 Ай бұрын
I agree. Using just the class was a more natural way, something anybody who comes expects how to use. The functions approach with the usage of 'partial' is very weird, even if it is a knownthing in the python world.
@eskuAdradit0
@eskuAdradit0 Жыл бұрын
The leading double underscores (and name mangling) is not at all meant to make things private, but rather to allow child classes to use that attribute as well. If you want to communicate that a certain method or attribute "is only meant for internal usage", a single leading underscore will do just fine. It will not be shown as part of the `__all__` variable, but it's also accessible. The best thing about not having private attributes in Python? Freedom.
@Femi-Kamau
@Femi-Kamau Жыл бұрын
Just when I thought the code couldn't be refactored any further, I looked at the timestamp and realised that I had 20 minutes of the video left. Thank you. I always learn so much from you. Loved the video!
@ArjanCodes
@ArjanCodes Жыл бұрын
Thank you so much Femi!
@mariocortes2670
@mariocortes2670 Жыл бұрын
I really love this kind of videos, where the code is improved while you explain the concepts.
@sprue_goose
@sprue_goose Жыл бұрын
These videos are awesome. Your pragmatic approach to teaching python through practical examples is quite frankly...awesome. Keep up the good work. I am an established programmer but still learning a lot from your dedication to the craft of coding,.
@ArjanCodes
@ArjanCodes Жыл бұрын
Thank you so much for sharing this! 💗
@vitalyromas6752
@vitalyromas6752 11 ай бұрын
Great lesson. The info is useful, but the way you are explaining the issues is amazing and efficient. Thank you.
@akin.kilic.
@akin.kilic. Жыл бұрын
I've been coding Python for 2+ years at work, and these videos still teach me new stuff. Appreciate it.
@hbbexxter4666
@hbbexxter4666 10 ай бұрын
Great work @Arjan, I have the impression that people often refuse to learn about OOP or stay away from it as much as possible as its complicated, but you clearly highlight using relevant use cases that this need not be the case. Thanks a lot for your work. Also, it appears worthwhile to take a deep dive into functools. Your tutorials are really handy. I cannot get enough of them, even at 3am on a Saturday morning. Any chance one can inspire you on a course about OOP and advanced concepts like multiple inheritance, the proper way of using ABC's and other advanced decorators?
@pillmuncher67
@pillmuncher67 11 ай бұрын
The double leading underscores are for Private Name Mangling and not for encapsulation, even if the name seems to suggest that. It is intended to avoid name clashes in Multiple-Inheritance scenarios. The leading single underscore is to tell the user of a class that they probably shouldn't use this attribute because it is an implementation detail and may change without notice. Real encapsulation is neither possible not wanted by anyone. As Guido always says: We're all consenting adults.
@loic1665
@loic1665 Жыл бұрын
I agree with you that when writing EmailSender = Callable[[str, str, str], None] you lose precious documentation about the arguments. Just by looking at this line, I have no idea what the arguments are, whereas it's perfectly clear using a Protocol. One way I've dealt with it in the past was doing something like this: ToEmail = str EmailSubject = str EmailBody = str EmailSender = Callable[[ToEmail, EmailSubject, EmailBody], None] This way it's clear again what the arguments are. I find it also clearer to define a function using a Callable compared to using a Protocol with __call__. I don't think it's perfect, tough, because I need to define a lot of type aliases here... What do you think? I'm curious about your opinions :)
@ArjanCodes
@ArjanCodes Жыл бұрын
I like that suggestion! It does solve the problem nicely. The only issue I see with this is that it’s actuality no longer clear what the types are: you now have to figure out that ToEmail is a string and not something else. Still a nice idea though, I hadn’t thought of this.
@loic1665
@loic1665 Жыл бұрын
Well, you have "ToEmail = str" just three lines above, so in my opinion it's still quite still what the type is. But I agree that this might just "move" the confusion elsewhere :)
@leo_desio_
@leo_desio_ 7 ай бұрын
Great content @Arjan. Clear and well explained!
@DMSBrian24
@DMSBrian24 10 ай бұрын
I like the "if your class has 2 methods and one of them is init, you should probably just use a function" approach. Ofc if you need multiple instances of sth or are writing interfaces or sth that's another story.
@saitaro
@saitaro Жыл бұрын
Thanks Arjan. I liked the phorfth fthing the most.
@hcubill
@hcubill 10 ай бұрын
Another awesome video by Arjan! I love so much these videos. I’m trying to get my company to do your course for my team :)🎉
@johnwalker4514
@johnwalker4514 Жыл бұрын
Great video, thanks! Would really like to see another go into a bit more detail on how to make clever use of ‘partial’
@ericalbertobernal101
@ericalbertobernal101 Жыл бұрын
Great Job !
@EW-mb1ih
@EW-mb1ih Жыл бұрын
Generally I try to avoid creating function in an object oriented code unless if they are very generic and could be applied to several classes. In your case, I wouldn't create bmi functions since the bmi calculation matches pretty well with the Stats class.
@josephmoorhouse4327
@josephmoorhouse4327 Жыл бұрын
Started using errorlens in vscode which IMO is a nicer way to see errors vs just squiggly lines 👍
@italobuitron1165
@italobuitron1165 Жыл бұрын
Hi Arjan! Love your videos, im watching 32/244 of your videos right now, just to thank you for all the content to make! Thanks a lot!
@ArjanCodes
@ArjanCodes Жыл бұрын
Thank you, I'm glad that they are helpful!
@mahmudhasan3093
@mahmudhasan3093 Жыл бұрын
Thank you
@BrianStDenis-pj1tq
@BrianStDenis-pj1tq 11 ай бұрын
"The fourth thing" repetition was awesome. Reminded me of friends of mine in college from Germany, who had to concentrate to make the "th" sound. They even made fun of themselves as you did.
@markgyamfi2144
@markgyamfi2144 11 ай бұрын
Nice video again. Really liked the part about using a module. One of the reasons I often find for classes are context managers. Do you happen to know if one could implement this in your module example as well. Although while thinking about it I don't see a use case for this 😅
@kosmonautofficial296
@kosmonautofficial296 Жыл бұрын
Great video! I didn't know about the lru_cache or cached_property that is really cool. Also didn't know you could type hint with a callable or instead use a class with __call__. I had heard of the double underscore attribute but didn't know it changed the naming like that. That is a lot of great information.
@ArjanCodes
@ArjanCodes Жыл бұрын
Thank you!
@codihuntsinger3698
@codihuntsinger3698 Жыл бұрын
Idk about cached_property decorator before 12:09. Thanks for share!
@MElixirDNB
@MElixirDNB Жыл бұрын
Great vid! Always love your clarity of examples. One small nit, that pylint helped me stop doing. Whenever you have an if condition: return, there shouldn't be an elif below it for another return, it should just be multiple if statements. See pylint R1705 no-else-return
@vitaliyk6909
@vitaliyk6909 Жыл бұрын
Amazing one! Thanks a lot! Especially for the abstraction part :-)
@ArjanCodes
@ArjanCodes Жыл бұрын
Thank you! ❤️
@user-lf1jn9rc5f
@user-lf1jn9rc5f 11 ай бұрын
Very nice video. I would like to have video about pattern, especially multiton pattern. Thank you !!
@saltis7229
@saltis7229 Жыл бұрын
Thank you kindly for your dedication to sharing knowledge! You have made my progress with python so much easier. Your production value is a clear breath of fresh air in a category mainly dominated by Indian KZbinrs
@ArjanCodes
@ArjanCodes Жыл бұрын
Thank you so much!
@kunle009
@kunle009 Жыл бұрын
I sincerely like the fact that this example is done using a calculation as an engineer this makes it more relatable for me. I am working to implement your concepts in my code. Thank you Arjan.
@ArjanCodes
@ArjanCodes Жыл бұрын
Thank you too!
@L1amTill
@L1amTill Жыл бұрын
Awesome video. Really liked all the tips. Ive been recently refactoring some code so this is good timing.
@ArjanCodes
@ArjanCodes Жыл бұрын
Thank you! 💗
@aungkyawkyaw9114
@aungkyawkyaw9114 Жыл бұрын
Thank so much. I am trying to integrate what he has been teaching and the video is a reminder that I am on the right approach.
@ArjanCodes
@ArjanCodes Жыл бұрын
Thank you, Aung!
@balakumar.n4891
@balakumar.n4891 Жыл бұрын
This is great masterclass!
@ArjanCodes
@ArjanCodes Жыл бұрын
Thank you! 💗
@Colaholiker
@Colaholiker Жыл бұрын
Another reason (for me) to use a class in Python, even if I only create a single instance, is when I have to keep track of a lot of state information that is modified by a bunch of methods. For example, think of an emulator for a microcontroller. You have a bunch of variables representing your registers, and functions implementing the individual opcodes that in turn modify your "registers". Sure, every function could use a bunch of "global" statements to get access to these variables, or you could create some object that contains all the data you need and explicitly pass it to the functions (basically hand-crafting the "self"), but for me, just having an object that keeps track of everything, both data and behavior, internally seems to be a better choice. just having an instruction like "cpu.mov_a_constant(value:int)" load a constant (passed as a parameter) into the internal representation of the a register (whatever that is) seemed to be the cleanest to me. I am *not* saying you are wrong about creating classes making sense when you plan on creating more than one instance, because I agree that this is the most important reason to do it. But I think there can be other (likely very specific) reasons to do so.
@asrajan55
@asrajan55 7 ай бұрын
Fantastic explanations!
@ArjanCodes
@ArjanCodes 7 ай бұрын
Thanks, I'm happy you enjoyed the content!
@obed818
@obed818 Жыл бұрын
Smell awesome will look soon!
@obed818
@obed818 Жыл бұрын
Misclicked the video lol
@mahbub_bro
@mahbub_bro Жыл бұрын
Great as always, ❤️
@ArjanCodes
@ArjanCodes Жыл бұрын
Thank you! ❤️
@ravenecho2410
@ravenecho2410 2 ай бұрын
U provide so much great insight, i love all ur videos. Im starting to learn rust, but is also nice to see how to design code in the language i understand the best U have helped me become a much better dev, i just wanted to say thanks 😊
@ArjanCodes
@ArjanCodes 2 ай бұрын
I'm happy to hear that I've been helpful in your learning journey :)
@rockNbrain
@rockNbrain 11 ай бұрын
Great job Arjan 🎉 tks
@ArjanCodes
@ArjanCodes 11 ай бұрын
Glad you liked it!
@seancahill442
@seancahill442 Жыл бұрын
Just want to say great video! Subscribed.
@ArjanCodes
@ArjanCodes Жыл бұрын
❤️
@adityavarshney6690
@adityavarshney6690 7 ай бұрын
Caching the float values for height/weight/bmi seems ineffective since the cache might be prone to floating point estimation error misses
@Penetal
@Penetal Жыл бұрын
Great video as usual, I do have 2 thoughts I would like some feedback on please. 1. It feels strange to move the bmi out to enable caching, is there no better way to have the method be cached, but invalidated when any property (or the relevant properties) are modified in the object? The @cache only returns the same result for the same input, I guess that does not work for the method (or cached_property) even though the "self" would be modified when the weight/height is modified? 2. It feels like a hack to another kind of uneeded Protocol class with __call__ to be able to use the email service as a function all to avoid another, somewhat unnecessary, class. Would it not be better (if possible) to use the typing library and NewType to make it more clear what the parameters in the Callable should be?
@EW-mb1ih
@EW-mb1ih Жыл бұрын
+1 to get a feedback on your questions
@joel-eq8tq
@joel-eq8tq Жыл бұрын
Brilliant tutorial as usual.
@ArjanCodes
@ArjanCodes Жыл бұрын
Thank you, Joel!
@michaelrstudley
@michaelrstudley 3 ай бұрын
This video is amazing. Great examples that seem a bit more real world vs the class Car: Color Year Examples that aren't helping me as I write my first program with classes (blackjack). Thank you
@ddctechinstitute6861
@ddctechinstitute6861 Жыл бұрын
Great
@victorRL01
@victorRL01 Жыл бұрын
I've written a piece of code that defines a class which I utilize to generate a single instance upon receiving a translation request. I chose to structure this as a class because each request embodies a node topology, where each sub-node carries distinct types, and thus, distinct rules and responsibilities. This class-based design helps maintain the integrity of the structure and its associated rules. However, I'm curious about your opinion on this. Do you think employing modules with methods could be a more effective approach?
@ksrsundar
@ksrsundar 11 ай бұрын
you are too good boss..
@legitjimmyjaylight8409
@legitjimmyjaylight8409 11 ай бұрын
You can enforce encapsulation by doing clever things with custom annotations.
@GOTHICforLIFE1
@GOTHICforLIFE1 Жыл бұрын
I see you're using VimMotions (or something similar). Imo it's a very good next step to get used to for hour audience (intermediate developers). Maybe you could run through that in a guide / series
@miyu545
@miyu545 6 ай бұрын
Holy crap, a lot to unpack but amazing explanation and code example.
@ArjanCodes
@ArjanCodes 6 ай бұрын
Thank you for the kind words! Just take it one step at a time :)
@manomancan
@manomancan Жыл бұрын
I don't always write classes in Python, but when I do, I 'init' for the long haul... (Patting myself on the back for that one). Thanks Arjan, for being a one-man university and stopping my Game of Thrones-length classes. (P.S.: I have another Python joke, but I'll have to 'return' to it later.)
@ArjanCodes
@ArjanCodes Жыл бұрын
Glad to hear you find the content helpful. I eagerly 'await' your next joke!
@AbdellahBilla
@AbdellahBilla Жыл бұрын
I'm 'listening' for any new joke events
@NagarajCruze
@NagarajCruze Жыл бұрын
I’ve ‘yielded’
@kevon217
@kevon217 Жыл бұрын
these jokes are a bit ‘abstract’
@PetrSzturc
@PetrSzturc 11 ай бұрын
18:22 you mentioned using modules in case you need just one instance, but what if you need to defer loading the variables for when actually used. Similar to properties or functions. And you don't want to use functions because those variables store simple objects/strings. Or simple dictionary access. But you really don't want to compute them on import as they could fail. So class it is? Or is there another approach? Thanks for video.
@neebftw
@neebftw 19 күн бұрын
Amazing content, learning so much from this and also the first time i see an IRL Syntax error 17:42 😂
@Han-ve8uh
@Han-ve8uh Жыл бұрын
20:31 is turning Callable to class EmailSender(protocol) good practice? If i read the typehint then jump to this definition, i would think that variable it's hinting is a class instance, when it's actually a function. Making it a class with __call__ to have better documentation of arguments seems to cause more trouble than it's worth. 21:32 Can i understand partial as analogous to inheritance in classes? If the business logic changes. it feels like more edits are needed to get the partial API correct compared to classes, or isit the same?
@DeKeL_BaYaZi
@DeKeL_BaYaZi 12 күн бұрын
Hi Arjan, Great content as always! I have a question for you: I noticed that VS code sometimes gives you indications when you break rules regarding to type. Im guessing that it's an extension because mine doesn't behave that way. If so, can you please send it's name? thank you!!
@sephirothu1290
@sephirothu1290 5 ай бұрын
Hey man I just wanted to say you're so awesome
@ArjanCodes
@ArjanCodes 5 ай бұрын
Thank you for the kind words ahah!
@kevinmorrissey9398
@kevinmorrissey9398 3 ай бұрын
@ArjanCodes I two questions. Do you speed up the video when you are typing? What's your average WPM typing speed? 😮
@stephen285
@stephen285 Жыл бұрын
thnx for the vid, you always query for a known instance of class object in memory, what if you had a huge python list of things (lists are strings, not instantiated objects in memory) and you wanted to pass that list in a for loop to query your class to return attribute info for class objects that match the strings, like querying a database, how do you do that without getting str attribute errors? Not one class tutorial on youtube explains this? Thanks
@connorblackler5217
@connorblackler5217 Жыл бұрын
Love the vid! what's that slick extension that auto suggests the python code? Seems very handy!
@ArjanCodes
@ArjanCodes Жыл бұрын
It is handy :). It's called Fig.
@connorblackler5217
@connorblackler5217 Жыл бұрын
@@ArjanCodes Greatly appreciated! Keep up the great vids :)
@frantisekcastek174
@frantisekcastek174 Жыл бұрын
You just leave me breathless... This video is more exciting than all John Wicks. Thank you for knowledge and inspiration 🙏
@ArjanCodes
@ArjanCodes Жыл бұрын
Oh wow, thank you!
@paulreynolds8050
@paulreynolds8050 11 ай бұрын
Love your videos. NOOB question please: I use dictionaries a lot (I love them) - instead of a dictionary, where relevant, perhaps should I be using a dataclass?
@sumedhrao4081
@sumedhrao4081 9 ай бұрын
If you are creating dictionaries as a way to get away from creating a structure, definitely. Through classes you get autocomplete, getters and setters and what not but if the purpose is to store 2 values and pass it on I would at least use a named tuple
@mikeciul8599
@mikeciul8599 11 ай бұрын
I've had issues with mypy failing to typecheck partial functions. As a result, I tend to use factories instead - I'll write a function that contains a nested function, and returns the nested function as a closure. Not sure if I used all those words correctly... :D def email_sender(smtp_server: str, port: str, email: str password: str) -> EmailSender: def send_message(to_email: str, subject: str, body: str) -> None: send_email(smtp_server=smtp_server, port=port, email=email, password=password, to_email=to_email, subject=subject, body=body) return send_message
@terrypmusic
@terrypmusic 11 ай бұрын
Nicee
@Vijay-Yarramsetty
@Vijay-Yarramsetty Жыл бұрын
logo looks beautiful
@ArjanCodes
@ArjanCodes Жыл бұрын
Thank you!
@robboerman9378
@robboerman9378 5 ай бұрын
I love that you don’t edit out the tongue breakers like fourth thing 😂 really great explanations again
@ArjanCodes
@ArjanCodes 5 ай бұрын
Those are the most fun ☺️
@Leonardo_A1
@Leonardo_A1 8 ай бұрын
Hi Arjan great Video. We should replace "THE" by "beh" :-) No idea where this word "the" comes from ??? CU Leonardo from Germany
@DaveParr
@DaveParr 11 ай бұрын
Love that you sold this on "Ultimate Class Guide" and low key slipped in "Secret Guide to Functions"
@tonghongchen4289
@tonghongchen4289 11 ай бұрын
Thanks from a PayPal engineer refactoring Python code
@ArjanCodes
@ArjanCodes 11 ай бұрын
Thank you so much!
@MaycolTeles
@MaycolTeles Жыл бұрын
Really cool lesson, as always! One thing I personally like to do in situations like the "bmi_category" example is to actually create a variable to "cache" the value. Something like: @property(self) -> str: bmi = self.bmi if bmi < 18.5: ... By doing this way we don't need to use the caching approach using decorators... It'd require to be done in each method, yes, but if we have only one (like in this case), I think it's a better solution!
@QuintinMassey
@QuintinMassey 5 ай бұрын
What about methods that span multiple classes, what’s the best way to handle that?
@Leonardo_A1
@Leonardo_A1 8 ай бұрын
Here atr some wishes from me ...okay okay it's not christmas time. 1. handling languages (tranalations) in a sw-product an it's maintance 2. Working with Interaces to other products (json, XML, API,direct Access as SAP-BAPIs, ...) 3.Error handling in Python (central vs decentral)? Thanks have a great time in Amsterdam
@maikwiesmueller
@maikwiesmueller Жыл бұрын
Great video! What do you think about DI frameworks in python?
@pelissargiosergio
@pelissargiosergio Жыл бұрын
I use DI, initially I was against it, but after starting to use, it is a must-have for my services.
@maikwiesmueller
@maikwiesmueller Жыл бұрын
@@pelissargiosergio yeah, but what lib, or no lib at all?
@pelissargiosergio
@pelissargiosergio Жыл бұрын
@@maikwiesmueller python-dependency-injector, I use this lib.
@jerdanro
@jerdanro 11 ай бұрын
What is your opinion of Static methods? Not to be too inflexible, but they seem to violate the principle of creating small, single purpose classes. Maybe they are necessary in other languages?
@waldospek107
@waldospek107 11 ай бұрын
I would say they are just like any other method; if they "belong to" the class conceptually, implement them instead of factoring them out as functions. By tagging them @staticmethod you are basically communicating: "this method will not change my class state". I would use @property only if the calculation inside is fast, because a user will not expect accesing a property to be taking a long time. If that is the case use static methods.
@user-mi2bb8bm6s
@user-mi2bb8bm6s Жыл бұрын
legend legend legend
@untildawn5714
@untildawn5714 8 ай бұрын
I was rejected because I used dependency injection instead of instantiating a service class in the main class of a 48hours home work for a tech job. What do you guys think? ( bit stock trading company )
@itnabigator
@itnabigator 5 ай бұрын
lru_cache on bmi function was a nice joke ;) replace 3 arithmetic operations with wrapper and fiddling cache dict and store all old values for what?
@gedtoon6451
@gedtoon6451 5 ай бұрын
Why put the instance of Stats into the Person class if you are going to call it directly?
@Impatient_Ape
@Impatient_Ape Жыл бұрын
This comment is not a criticism of the purpose of the video -- just a (subjective) suggestion for viewers who read these comments. The name "Biometrics" might be a better name for what Arjan called the "Stats" class, since it's more specific to what the class represents. In most contexts, "stats" often refers to the data which *changes*. In medicine, it's things like heart rate, blood pressure, amounts of stuff in blood tests, etc. It is usually worth the time to think of good class names, since it's a real pain to change them 150 commits later into your project when you realize that "Stats" would be the perfect name for a class containing a set of regularly measured/changing data.
@RitchieDiamond
@RitchieDiamond 11 ай бұрын
Not sure why the type checker did not pick up on this, but technically your EmailSender Protocol (the __call__ variant) around 21:00 is lying to consumers of that type, because it looks like you can provide positional arguments to the supplied partial function, but you actually need to provide keyword arguments (otherwise running into the crash you showcased in the video). You can enforce keyword-only arguments as follows: def f(*, a): ... Here, the function f will take one keyword-only argument a.
@thisoldproperty
@thisoldproperty Жыл бұрын
I thought you’d like the lru_cache and property comment. I’m glad Python is all open source.
@tunedone4033
@tunedone4033 Жыл бұрын
Like for video and for video preview))))
@ArjanCodes
@ArjanCodes Жыл бұрын
Thank you! 😎
@zikomo8913
@zikomo8913 Жыл бұрын
LOL the thumbnail. 10 Points to Gryffindor...
@ArjanCodes
@ArjanCodes Жыл бұрын
🪄 😉
@dev.aaajit
@dev.aaajit Жыл бұрын
What's the autocompletion vscode extension ?
@ArjanCodes
@ArjanCodes Жыл бұрын
It's called Fig!
@perrinromney4555
@perrinromney4555 11 ай бұрын
Been hobby coding for two years now and had no idea half of this stuff existed.
@chapmansbg
@chapmansbg Жыл бұрын
Why are you using static information? For create person.
@ravenecho2410
@ravenecho2410 11 ай бұрын
once could use a closure as a way to capture state, but meh python isnt that functional and no idea what it does with memory
@gASP987
@gASP987 Жыл бұрын
why not an id attr in Person?
@JusticeNDOU
@JusticeNDOU 4 ай бұрын
Arjan i dont understand your love of neon lights man, anyways long ttime fan here
@danielgsfb
@danielgsfb Ай бұрын
calling a method straight from the stats instance outside the person would lead to unexpected behavior.
@dirtdart81
@dirtdart81 Жыл бұрын
Amazing thumbnail lol
@ArjanCodes
@ArjanCodes Жыл бұрын
Haha, thanks :)
@vivekveeramani87
@vivekveeramani87 Жыл бұрын
TLDR: No, there's no TLDR to this. Dont miss this brilliant talk 🙂. Its worth it !
@ArjanCodes
@ArjanCodes Жыл бұрын
Thank you so much!
@coopernik
@coopernik 6 ай бұрын
im a bit of a noob but why do your classes not have the constructor method?
@ArjanCodes
@ArjanCodes 6 ай бұрын
I’m often using dataclasses. If you do that, the initializer is generated automatically.
@kslader8
@kslader8 Жыл бұрын
I find _method is more commonly used for private (even though if you google it you will find articles that say _method is protected and __method is private). I don't think the concept of protected really exists in python in opinion Great video as always too. I really love your content. I find that watching your video helps me better articulate my opinions to other developers.
@randypittman279
@randypittman279 11 ай бұрын
_method() means "you probably shouldn't use this unless you know what you're doing", where __method() is very difficult to use outside the class as the name mangling means you have to access it with _ClassName__method(). Nevertheless, it is possible to access it, so it isn't truly private. It's just a super big red flag to use it outside the class.
@FridolinRath
@FridolinRath 11 ай бұрын
Hi Arjan, greetings from Germany! You are doing an amazing job with this channel and I am recommending it a lot: Regarding the current video with the function bmi_category, I would like to know your opinion or your suggestion. I hate all this if-elif-else stuff, so I try to do something around. here is my idea: def bmi_category(bmi_value: float) -> str: _category = { 'Underweight': lambda __: 0 < __ < 18.5, 'Normal': lambda __: 18.5 < __ < 25.0, 'Overweight': lambda __: 25.0 < __ < 30.0, 'Obese': lambda __: 30.0 < __ } return ''.join(_k for _k, _v in _category.items() if _v(bmi_value)) print(bmi_category(17)) # Underweight print(bmi_category(19)) # Normal print(bmi_category(27)) # Overweight print(bmi_category(50)) # Obese print(bmi_category(-14)) # '' => empty string What do you think?
@user-gv8ck6je5c
@user-gv8ck6je5c 4 ай бұрын
Why did you complicate sending email from a lru_cache method, i appreciate the techniques but this feels unreadable and unnecessary 2x code.
@Snifo
@Snifo Жыл бұрын
where is __slots__ :(
@ArjanCodes
@ArjanCodes Жыл бұрын
I focused on design in this video. Slots is mostly a performance improvement, so I decided to leave it out.
@gshan994
@gshan994 10 ай бұрын
Email. Service class could have been dataclass
@FighterAceee94
@FighterAceee94 Жыл бұрын
If you think a person class has too many instance variables, try a ship class... this is what I'm dealing with. To name a few: Ship name, Ship number, IMO number, Ship type, Rule length, [m], Length overall, [m], Depth, [m], Breadth, [m], Draught (maximum), [m], Draught (loading condition, current), [m], Draught (lightship), [m], Draught (light ballast condition), [m], Displacement, [t], Deadweight, [t], Foremost cargo hold/tank bukhead to FE, [m], Aftmost cargo hold/tank bukhead to AE, [m], Foremost nonstructural cargo tank edge to foremost cargo hold/tank bukhead, [m], Aftmost nonstructural cargo tank edge to aftmost cargo hold/tank bukhead, [m], Bottom or inner bottom vertical coordinate, [m], Aft end of the hull to AE, [m], Aft end of the waterline (WL) to AE, [m], Aft end of the hull to aft end of waterline (WL), [m], Fwd end of the hull to fwd end of waterline (WL), [m], Double bottom water ballast tanks (Boolean), Collision buklhead, [m], Aft peak buklhead, [m]
@hansdietrich1496
@hansdietrich1496 Жыл бұрын
Some nit picking: In terms of naming the classes: "Stats" doesn't seem ideal to me. It says nothing about what you have inside of the class. You don't do statistics. It would probably better be called "MedicalData". Also, "age" is something that changes every day. Time is running ... Better to store date_of_birth and calculate "age" with a property.
@bernard3992
@bernard3992 Жыл бұрын
That's not even the point of the video.
@RitchieDiamond
@RitchieDiamond 11 ай бұрын
@@bernard3992 it is because one part of class design is to minimize changes required in the future, which requires solid naming and appropriate data (structures).
Functions vs Classes: When to Use Which and Why?
10:49
ArjanCodes
Рет қаралды 136 М.
The Ultimate Guide to Writing Functions
24:31
ArjanCodes
Рет қаралды 175 М.
NO NO NO YES! (50 MLN SUBSCRIBERS CHALLENGE!) #shorts
00:26
PANDA BOI
Рет қаралды 86 МЛН
Зу-зу Күлпәш. Агроном. (5-бөлім)
55:20
ASTANATV Movie
Рет қаралды 653 М.
Uma Ki Super Power To Dekho 😂
00:15
Uma Bai
Рет қаралды 51 МЛН
Dependency INVERSION vs Dependency INJECTION in Python
17:51
ArjanCodes
Рет қаралды 152 М.
Learn Python Classes With a Text-Based Battle - OOP Tutorial
15:25
Ork Slayer Gamedev
Рет қаралды 122 М.
Python Classes Tutorial #5 | Advanced Concepts
10:08
Aikonic
Рет қаралды 3,1 М.
5 Useful Dunder Methods In Python
16:10
Indently
Рет қаралды 46 М.
You Can Do Really Cool Things With Functions In Python
19:47
ArjanCodes
Рет қаралды 214 М.
5 Tips To Achieve Low Coupling In Your Python Code
18:30
ArjanCodes
Рет қаралды 93 М.
5 Tips To Write Better Python Functions
15:59
Indently
Рет қаралды 69 М.
7 Python Code Smells: Olfactory Offenses To Avoid At All Costs
22:10
Why Use Design Patterns When Python Has Functions?
23:23
ArjanCodes
Рет қаралды 96 М.
10 Python Comprehensions You SHOULD Be Using
21:35
Tech With Tim
Рет қаралды 92 М.
NO NO NO YES! (50 MLN SUBSCRIBERS CHALLENGE!) #shorts
00:26
PANDA BOI
Рет қаралды 86 МЛН