PythonObject Oriented Programming

Python Class Members: Mastering Attributes and Methods

TT
TopicTrick
Python Class Members: Mastering Attributes and Methods

Introduction to Class Members

In our previous tutorial, we covered the basics of Python OOP. Now, let's explore the "members" of a class—the variables and methods that give your objects data and functionality.

Typically, a Python class consists of:

  • Docstrings: For documentation.
  • Built-in Attributes: Predefined metadata.
  • Variables: To store state (Instance, Class, Private).
  • Methods: To define behavior (Instance, Class, Static, Magic).

1. Docstrings & Built-in Attributes

Docstrings

A docstring is a string literal used to describe the purpose of your class or method. It’s accessed via the __doc__ attribute.

python
1class Student: 2 """This class represents a Student template for academic records.""" 3 pass 4 5print(Student.__doc__)

Essential Built-in Attributes

Every Python class comes with several built-in attributes that provide metadata:

AttributeDescription
__name__Returns the name of the class.
__module__Returns the name of the module where the class is defined.
__bases__Returns a tuple of base classes (parent classes).
__dict__Returns a dictionary containing the class's namespace.

2. Types of Variables

Instance Variables

These are unique to each object. Every instance has its own copy, and changing one doesn't affect the others. They are usually defined inside the __init__ constructor.

python
1class Student: 2 def __init__(self, name, student_id): 3 self.name = name # Instance Variable 4 self.id = student_id # Instance Variable 5 6s1 = Student("David", "001") 7s2 = Student("Harry", "002")

Class Variables

These are shared by ALL instances of a class. They are defined outside the constructor.

python
1class Student: 2 school_name = "TopicTrick Academy" # Class Variable 3 4 def __init__(self, name): 5 self.name = name 6 7print(Student.school_name) # Shared by all students

Avoid Altering Class Variables via Instances

If you do `instance.classvariable = newvalue`, Python creates a NEW instance variable for that specific object instead of changing the class-wide value. Always use `ClassName.variablename` to update class variables.

    Private Variables (Name Mangling)

    Python doesn't have true "private" variables, but it uses a convention called Name Mangling. Any attribute starting with __ (double underscore) is "hidden."

    python
    1class Student: 2 def __init__(self, grade): 3 self.__grade = grade # Private-ish variable 4 5s = Student("A+") 6# print(s.__grade) -> Throws AttributeError 7print(s._Student__grade) # Accessed via mangled name

    3. Types of Methods

    Instance Methods

    The most common type. They take self as the first argument and can access/modify instance-specific data.

    python
    1class Student: 2 def introduce(self): 3 print(f"Hi, I'm {self.name}")

    Class Methods

    Bound to the class itself, not the instance. They take cls as the first argument and are marked with the @classmethod decorator. Use them for factory methods or modifying class state.

    python
    1class Student: 2 count = 0 3 @classmethod 4 def increment_count(cls): 5 cls.count += 1

    Static Methods

    These don't take self or cls. They act like regular functions but are grouped within the class for organization (Utility functions).

    python
    1class Student: 2 @staticmethod 3 def validate_id(id_str): 4 return len(id_str) == 5

    Magic (Dunder) Methods

    These have double underscores (e.g., __init__, __str__). They allow you to perform special operations like operator overloading.


    Conclusion

    Understanding the difference between these members is key to writing clean, efficient OOP code. You now know how to manage shared data with Class Variables, protect data with Private Variables, and organize logic with Static Methods.

    What's Next?

    Up next, we'll explore Inheritance and how to reuse code across multiple classes!