[{"data":1,"prerenderedAt":78},["ShallowReactive",2],{"qa-\u002Fpython\u002Foop\u002Fclasses":3},{"page":4,"siblings":56,"blog":47},{"id":5,"title":6,"body":7,"description":11,"difficulty":14,"extension":15,"framework":16,"frameworkSlug":17,"meta":18,"navigation":19,"order":12,"path":20,"questions":21,"related":47,"seo":48,"seoDescription":49,"stem":50,"subtopic":51,"topic":52,"topicSlug":53,"updated":54,"__hash__":55},"qa\u002Fpython\u002Foop\u002Fclasses.md","Classes",{"type":8,"value":9,"toc":10},"minimark",[],{"title":11,"searchDepth":12,"depth":12,"links":13},"",2,[],"easy","md","Python","python",{},true,"\u002Fpython\u002Foop\u002Fclasses",[22,26,31,35,39,43],{"id":23,"difficulty":14,"q":24,"a":25},"class-vs-instance","What is the difference between a class and an instance?","A **class** is a **blueprint** — it defines the attributes and methods that\nobjects of that type will have. An **instance** is a concrete **object built\nfrom that blueprint**, with its own state. You write the class once and create\nmany instances from it.\n\n```python\nclass Dog:                 # the blueprint\n    def __init__(self, name):\n        self.name = name   # per-instance state\n\nrex = Dog(\"Rex\")           # an instance\nfido = Dog(\"Fido\")         # a separate instance\nrex.name                   # 'Rex'\nfido.name                  # 'Fido' — independent state\ntype(rex)                  # \u003Cclass '__main__.Dog'>\n```\n\nThe class itself is also an object (of type `type`). Each instance carries its\nown data but shares the class's methods. Think of the class as the cookie\ncutter and the instances as the cookies.\n",{"id":27,"difficulty":28,"q":29,"a":30},"init-vs-new","medium","What is the difference between __init__ and __new__?","`__new__` **creates and returns the new object**; `__init__` **initializes**\nthat already-created object. `__new__` runs first and is a static method that\nreceives the **class**; `__init__` runs second and receives the **instance**\n(`self`) it should configure. `__init__` must return `None`.\n\n```python\nclass Widget:\n    def __new__(cls, *args):\n        print(\"__new__ — allocating\")\n        return super().__new__(cls)   # returns the instance\n    def __init__(self, size):\n        print(\"__init__ — configuring\")\n        self.size = size              # sets state on self\n\nw = Widget(10)   # prints __new__ then __init__\n```\n\nYou rarely override `__new__` — it's mainly for **immutable types** (subclassing\n`int`\u002F`str`\u002F`tuple`), singletons, or metaclass tricks. For everyday classes,\njust use `__init__`.\n",{"id":32,"difficulty":14,"q":33,"a":34},"what-is-self","What is `self` in Python?","`self` is the **instance the method was called on** — it's how a method accesses\nthat object's attributes and other methods. It isn't a keyword; it's just the\nconventional **name of the first parameter**. Python passes the instance\nautomatically when you call `obj.method()`.\n\n```python\nclass Counter:\n    def __init__(self):\n        self.count = 0\n    def increment(self):\n        self.count += 1        # self refers to this instance\n\nc = Counter()\nc.increment()                  # Python passes c as self\nCounter.increment(c)           # exactly equivalent — self is explicit here\n```\n\nSo `c.increment()` is sugar for `Counter.increment(c)`. The explicitness is\ndeliberate — Python makes the instance visible rather than hiding it like\n`this` in other languages.\n",{"id":36,"difficulty":28,"q":37,"a":38},"instance-vs-class-attributes","What is the difference between instance and class attributes?","A **class attribute** is defined in the class body and **shared by every\ninstance**; an **instance attribute** is set on `self` (usually in `__init__`)\nand is **unique per object**. Attribute lookup checks the instance first, then\nfalls back to the class.\n\n```python\nclass Dog:\n    species = \"Canis familiaris\"   # class attribute — shared\n    def __init__(self, name):\n        self.name = name           # instance attribute — per-object\n\na, b = Dog(\"Rex\"), Dog(\"Fido\")\na.species                # 'Canis familiaris' (from the class)\na.name, b.name           # 'Rex', 'Fido' (independent)\na.species = \"wolf\"       # creates an instance attr that SHADOWS the class one\nb.species                # still 'Canis familiaris'\n```\n\nWatch the classic trap: a **mutable** class attribute (like `[]`) is shared and\nwill leak state between instances — initialize mutable state in `__init__`.\n",{"id":40,"difficulty":28,"q":41,"a":42},"repr-vs-str","What is the difference between __repr__ and __str__?","`__repr__` is the **unambiguous, developer-facing** representation — ideally\nsomething that could recreate the object — and is what you see in the REPL and\nin containers. `__str__` is the **readable, user-facing** string used by\n`print()` and `str()`. If `__str__` is missing, Python **falls back to\n`__repr__`**.\n\n```python\nclass Point:\n    def __init__(self, x, y):\n        self.x, self.y = x, y\n    def __repr__(self):\n        return f\"Point(x={self.x}, y={self.y})\"   # for developers\n    def __str__(self):\n        return f\"({self.x}, {self.y})\"            # for users\n\np = Point(1, 2)\nprint(p)     # (1, 2)        — __str__\nrepr(p)      # 'Point(x=1, y=2)'  — __repr__\n[p]          # [Point(x=1, y=2)]  — containers use __repr__\n```\n\nRule of thumb: always define `__repr__`; add `__str__` only when you need a\ndistinct friendly form.\n",{"id":44,"difficulty":28,"q":45,"a":46},"object-creation-flow","What happens, step by step, when you call ClassName()?","Calling `ClassName(args)` invokes the class's metaclass `__call__`, which\norchestrates two steps: it calls **`__new__(cls, args)`** to allocate the\nobject, then — if `__new__` returned an instance of `cls` — calls\n**`__init__(instance, args)`** to initialize it, and finally returns the\ninstance.\n\n```python\nclass Demo:\n    def __new__(cls, *a):\n        print(\"1. __new__\")\n        return super().__new__(cls)\n    def __init__(self, *a):\n        print(\"2. __init__\")\n\nd = Demo()       # prints: 1. __new__  then  2. __init__\n# 3. d is now bound to the fully initialized instance\n```\n\nKey subtlety: if `__new__` returns an object that is **not** an instance of the\nclass, `__init__` is **skipped entirely**. For normal classes you never see\nthis machinery — you just call the class and get back a ready object.\n",null,{"description":11},"Python interview questions on classes vs instances, __init__ vs __new__, the self parameter, instance vs class attributes, __repr__ vs __str__, and the object creation flow.","python\u002Foop\u002Fclasses","Classes, Instances & __init__","Object-Oriented Programming","oop","2026-06-18","ouDK0ESDWwDR7Ofpyzn1mO8dgBG_yOsNKMgJuy_V_Uo",[57,61,62,66,70,74],{"subtopic":58,"path":59,"order":60},"Inheritance & the MRO","\u002Fpython\u002Foop\u002Finheritance",1,{"subtopic":51,"path":20,"order":12},{"subtopic":63,"path":64,"order":65},"Dunder \u002F Magic Methods","\u002Fpython\u002Foop\u002Fdunder-methods",3,{"subtopic":67,"path":68,"order":69},"Methods & Properties","\u002Fpython\u002Foop\u002Fmethods-properties",4,{"subtopic":71,"path":72,"order":73},"Dataclasses & __slots__","\u002Fpython\u002Foop\u002Fdataclasses-slots",5,{"subtopic":75,"path":76,"order":77},"Abstract Base Classes & Protocols","\u002Fpython\u002Foop\u002Fabc-protocols",6,1781808680135]