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

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.