Home » Python » Python programs

Python example to define a class

Defining a class in Python: In this program/example, we are going to learn how to define a class, how to define an attribute, how to create an object of the class and how to access the attribute?
Submitted by IncludeHelp, on August 06, 2019

The task to define a class in Python.

Here, we are defining a class named Number with an attribute num, initializing it with a value 123, then creating two objects N1 and N2 and finally, printing the object's memory locations and attributes value using the object names.

Python code to define a class

# Python code to define a class

# class definition
class Number():
    #Attribute
    num = 123

# main code
if __name__ == "__main__": 
    # creating first object 
    N1 = Number()
    #Printing object's memory (in hexadecimal)
    print(N1)      
    #Accessing and printing Class's Attribute
    print(N1.num)  

    # creating first object 
    N2 = Number()
    #Printing object's memory (in hexadecimal)
    print(N2)      
    #Accessing and printing Class's Attribute
    print(N2.num)

Output

<__main__.Number object at 0x7f96c06a0160>
123
<__main__.Number object at 0x7f96c06a06d8>
123


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.