Python Objects & Attributes Belonging to a Class

post

Learn Python classes, objects, attributes, and how to delete them. Python is object-oriented and models real-world entities with ease.

What is a Python Class?

A class is a blueprint or template for creating objects. It defines a type but doesn’t hold any actual data itself. Think of it as an abstract data type or prototype.

Let’s explore how Python classes work in detail.

Python Class Syntax

1. Defining a Python Class

To define a class, use the class keyword—similar to how def is used to define a function. A class can also have a docstring that explains its purpose.

Example:

class Fruit:    """    This Python class creates instances of fruits    """    pass 

As soon as a class is defined, a class object is created.

Fruit # Output: <class '__main__.Fruit'> 

Classes can have attributes and methods, defined in the usual way.

class Fruit:    """    This class creates instances of fruits    """    color = ''        def say_hi(self):        print("Hi") orange = Fruit()

Here, color is an attribute and say_hi() is a method. You can also define a function inside a method:

class Try1:    def my_method(self):        def say_hello():            print("Hello")        print("Hi")        say_hello() obj1 = Try1() obj1.my_method() # Output: # Hi # Hello 

You can even add attributes dynamically:

orange.shape = 'Round' orange.shape # Output: 'Round' 

2. Accessing Class Members

To access class members, use the dot operator:

orange = Fruit() orange.color # Output: '' (empty string) orange.say_hi() # Output: Hi 

You can also define methods with parameters:

class Fruit:    def size(self, x):        print(f"I am size {x}") orange = Fruit() orange.size(7) # Output: I am size 7 

Classes also support special attributes like __doc__:

Fruit.__doc__ # Output: '\n\tThis class creates instances of fruits\n\t' 

Let’s see an example with the __init__() method and self:

class Fruit:    def __init__(self, color, size):        self.color = color        self.size = size    def salutation(self):        print(f"I am {self.color} and size {self.size}") orange = Fruit('Orange', 7) orange.salutation() # Output: I am Orange and size 7 

Here, __init__() is the constructor, and self refers to the current instance, similar to this in Java. You can name it anything, but self is the convention.

Fruit.salutation # Output: <function Fruit.salutation at ...> orange.salutation # Output: <bound method Fruit.salutation of <__main__.Fruit object at ...>> say_hi = orange.salutation say_hi() # Output: I am Orange and size 7 

What is a Python Object?

A class is just an idea; an object is its execution. When you create an object, __init__() is called and attributes are assigned.

orange = Fruit('Orange', 7)

You can assign attributes on the fly:

orange.shape = 'Round' orange.shape # Output: 'Round' 

You can also assign one object to another:

apple = orange apple.color # Output: 'Orange' 

Class-level Attributes

Let’s redefine the class to include a class-level attribute:

class Fruit:    size = 'Small'    def __init__(self, color, shape):        self.color = color        self.shape = shape    def salutation(self):        print(f"I am {self.color} and shape {self.shape}")

Here, size belongs to the class but can still be accessed through an instance:

Fruit.size # Output: 'Small' orange = Fruit('Orange', 'Round') orange.size # Output: 'Small' 

A class can also contain a simple function:

class Fruit:    size = 'Small'    def __init__(self, color, shape):        self.color = color        self.shape = shape    def salutation():        print("I am happy") Fruit.salutation() # Output: I am happy 

Deleting a Python Class, Attribute, or Object

You can delete attributes, objects, or entire classes using the del keyword:

del orange.shape # Accessing orange.shape now gives an error del orange # Accessing orange now gives an error del Fruit # Accessing Fruit now gives an error 

Python Interview Questions on Class

What is a class in Python? Explain with example.

How do you call a class in Python?

Are Python classes slow?

When should you use classes in Python?

How do you define a class in Python?

Conclusion

In this Python Class tutorial by Debugshala, we learned about Python classes, how to create objects, access and define attributes and methods, and how to delete them when needed.


Share This Job:

Write A Comment

    No Comments