![I Don't Like Magic * Exploring The Class Attributes That Aren't Really Class Attributes * [Club]](https://substackcdn.com/image/fetch/$s_!HoKw!,f_auto,q_auto:best,fl_progressive:steep/https%3A%2F%2Fthepythoncodingstack.substack.com%2Ftwitter%2Fsubscribe-card.jpg%3Fv%3D-1980961260%26version%3D9)
"I don't like magic. I don't mean the magic of the Harry Potter kind-that one I'd like if only I could have it. It's the "magic" that happens behind the scenes when a programming language like Python does things out of sight. You'll often find things you have to "just learn" along the Python learning journey. "That's the way things are," you're told."
"Here's what I mean. Let's look at a standard class first: class Person: classification = "Human" def __init__(self, name, age, profession): self.name = name self.age = age self.profession = profession You define a class attribute, .classification, inside the class block, but outside any of the special methods. All instances will share this class attribute. Then you define the .__init__() special method and create three instance attributes: .name, .age, and .profession. Each instance will have its own versions of these instance attributes."
Hidden behaviors in programming languages can feel like 'magic' when operations happen behind the scenes. NamedTuple from typing and dataclasses share similar class-block syntax that can confuse learners who expect explicit attribute assignments. A standard class defines class attributes inside the class block and instance attributes inside __init__, so class attributes are shared and instance attributes are per-object. Using dataclass simplifies data-only classes by declaring fields with type annotations, removing the need for explicit __init__ code. The shared syntax between NamedTuple and dataclass can obscure which behaviors are automatic versus explicit, causing conceptual friction.
Read at Thepythoncodingstack
Unable to calculate read time
Collection
[
|
...
]