Attributes and some Special Method in Python

kameshcodes

Attributes\textbf{Attributes}


  • Attributes are variables that belong to a class or an object.
  • They hold the state/data of an object or sometimes of the class itself.

Types of Attributes

Class Attributes\text{Class Attributes}

  • Defined directly in the class body (outside methods).
  • Shared across all objects of that class.
  • Exists even before any object is created.

Instance Attributes\text{Instance Attributes}

  • Defined inside methods (usually init) using self.
  • Unique to each object -> every object has its own copy.
  • Created after object instantiation.
class Student:
  school = 'Green Lawns' # This is class attribute
  def __init__(self, name, age):
      self.name = name # These two are instance attributes.
      self.age = age
st1 = Student('Kamesh', 25)
st2 = Student('Priya', 23)

After creating objects st1 and st2, each instance (st1 and st2) has its own unique name and age.

However, both st1 and st2 share the same school attribute, which is defined at the class level.


Remark:\text{Remark:} When you do obj.attr, Python looks in this order:


  1. Instance attributes (self.attr)
  2. If not found → Class attributes (ClassName.attr)
  3. If not found → Parent classes (inheritance chain)
  4. If still not found → AttributeError
st1.name # python looks into object itself and find name attached to self.
'Kamesh'
st1.school # If the object doesn’t have that attribute, Python looks in its class, if its not get, looks for parents, grandparent class if those exist.
'Green Lawns'
st1.father_name # If neither the object, nor the class, nor the parents have it, Python gives up.
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/tmp/ipython-input-3344927339.py in <cell line: 0>()
----> 1 st1.father_name # If neither the object, nor the class, nor the parents have it, Python gives up.

AttributeError: 'Student' object has no attribute 'father_name'

Special Method\textbf{Special Method}


str vs repr

If you ever created a class in Python or followed along till here, you must be familiar with one special method: __init__ and there are a few more special methods you should know. The most important ones are str and repr. They control how objects are turned into strings.

Both return string representations, but with different purposes:

  • str is meant for humans, while
  • repr is meant for developers.


  1. str

str gives a readable, user-friendly description of the object

class Student:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  # def __str__(self):
  #   return f"{self.name} ({self.age})"
st = Student('Kamesh', 25)
print(st)
<__main__.Student object at 0x78f2119489e0>

without str, Python shows a random memory address when you print obj, who can read '0x7bdcb29d51f0\text{0x7bdcb29d51f0}' and guess its Kamesh, 2525?


class Student:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def __str__(self):
    return f"{self.name} ({self.age})"
st = Student('Kamesh', 25)
print(st)
Kamesh (25)
  1. repr
  • repr is a special method in Python that returns an unambiguous, developer-focused string representation of an object.

  • Its primary goal is precision and clarity, making it especially useful for debugging.

  • Ideally, the string it returns should be written in such a way that if you copy and paste it back into Python, it could recreate the same object.

class Student:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def __repr__(self):
    return f"Student(name={self.name}, age={self.age})"
st = Student('Kamesh', 25)

repr(st)
'Student(name=Kamesh, age=25)'
st
Student(name=Kamesh, age=25)

Remark:

  • print(st) \rightarrow Python first looks for str.
    • If str is defined \rightarrow it uses that
    • If not \rightarrow it falls back to repr
class Student:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def __str__(self):
    return f"{self.name} ({self.age})"

  def __repr__(self):
    return f"Student(name={self.name}, age={self.age})"
st = Student('Kamesh', 25)
print(st)
Kamesh (25)
str(st)
'Kamesh (25)'
repr(st)
'Student(name=Kamesh, age=25)'
st
Student(name=Kamesh, age=25)

Note:

  • print(st) \rightarrow prefers str, falls back to repr.

  • st (by itself) \rightarrow always repr.

Made with REPL Notes Build your own website in minutes with Jupyter notebooks.