MENU

Fun & Interesting

If You’re Not Using Python DATA CLASSES Yet, You Should 🚀

ArjanCodes 323,811 4 years ago
Video Not Working? Fix It Now

💡 Learn how to design great software in 7 steps: https://arjan.codes/designguide. This video is a tutorial about Python's dataclasses. I take you through an example that shows what you can do with them. Python data classes are - as you'd expect - in particular suitable to model classes that represent data, and as such they offer easy mechanisms to initialize, print, order, sort, and compare data. Note that although I'm using a sort_index attribute, strictly speaking that's not needed in this case, because a data class uses a tuple of its attributes in the class definition as the default for sorting. I'm not a fan of this kind of hidden behavior, so I prefer to do it explicitly (using something that is called sort_index in this case). Another advantage of using a separate field, is that you can do more complicated ordering, using for example a weighted combination of age and strength. 🎓 ArjanCodes Courses: https://www.arjancodes.com/courses/ 🔖 Chapters: 0:00 Intro 0:33 Behavior-driven vs data-driven classes 2:11 Explaining the example 3:31 Creating a dataclass 4:37 Sorting and comparing 6:58 Default values 7:40 Creating read-only (frozen) objects 8:55 String representation of data 9:34 Final thoughts #arjancodes #softwaredesign #python

Comment