What is class? How do we define class? How class members are accessed? Explain with examples

What is class? How do we define class? How class members are accessed? Explain with examples

Class

A class is a programmer-defined type that acts as a blueprint for creating objects. It encapsulates data (attributes) and functions (methods) into a single unit. A class object can be used to create instances of the type.

Defining a Class (from 15.1)

class Point:
    """Represents a point in 2-D space."""

This defines a class named Point with a docstring explaining its purpose.

Creating an Object (Instance)
Creating an object is known as instantiation.

blank = Point()

Here, blank is an instance of the Point class.

Assigning and Accessing Attributes (from 15.2)

blank.x = 3.0
blank.y = 4.0

print(blank.x)  # Output: 3.0
print(blank.y)  # Output: 4.0

You can assign values using dot notation and access them similarly.

Using in Expressions

import math
distance = math.sqrt(blank.x**2 + blank.y**2)
print(distance)  # Output: 5.0

Passing Instance to a Function

def print_point(p):
    print('(%g, %g)' % (p.x, p.y))

print_point(blank)  # Output: (3.0, 4.0)

Here, the object is passed to a function like any other argument. The function accesses the object’s attributes using dot notation.

Conclusion

  • A class is defined using the class keyword.
  • Attributes and methods are accessed using dot notation.
  • Objects are mutable, and attributes can be modified at any time.
  • Functions can receive and operate on objects as arguments.

Leave a Reply

Your email address will not be published. Required fields are marked *