Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Create a Python Subclass
Next article icon

Class attributes:Class attributes belong to the class itself they will be shared by all the instances. Such attributes are defined in the class body parts usually at the top, for legibility.

Python
# Write Python code hereclasssampleclass:count=0# class attributedefincrease(self):sampleclass.count+=1# Calling increase() on an objects1=sampleclass()s1.increase()print(s1.count)# Calling increase on one more# objects2=sampleclass()s2.increase()print(s2.count)print(sampleclass.count)

Output:

1              2                           2

Instance Attributes

Unlike class attributes, instance attributes are not shared by objects. Every object has its own copy of the instance attribute (In case of class attributes all object refer to single copy). To list the attributes of an instance/object, we have two functions:- 1.

vars() - This function displays the attribute of an instance in the form of an dictionary. 2.

dir() - This function displays more attributes than vars function,as it is not limited to instance. It displays the class attributes as well. It also displays the attributes of its ancestor classes.

Python
# Python program to demonstrate# instance attributes.classemp:def__init__(self):self.name='xyz'self.salary=4000defshow(self):print(self.name)print(self.salary)e1=emp()print("Dictionary form :",vars(e1))print(dir(e1))

Output :

Dictionary form :{'salary': 4000, 'name': 'xyz'}['__doc__', '__init__', '__module__', 'name', 'salary', 'show']

Class Instance Attributes in Python
Visit Courseexplore course icon

I

It_Wasnt_Me
Improve
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp