Python Class Attributes VS Instance Attributes

  • What’s a class attribute
  • How to create it
""" Module Rectangle"""class Rectangle:   """ a rectangle class that define a rectangle"""   pass
""" Module Rectangle"""class Rectangle:   """ a rectangle class that define a rectangle"""   # A class variable, counting the number of instances   number_of_instances = 1
print("{:d} instances of Rectangle".format(Rectangle.number_of_instances))
1 instances of Rectangle
  • What’s an instance attribute

Creating Instance Pythonic and non-Pythonic

""" Module Rectangle"""class Rectangle:   """ a rectangle class that define a rectangle"""def __init__(self,width=0, height=0):
if not (isinstance(width, int) or isinstance(height, int)):
raise TypeError("size must be an integer")

if width < 0 or height < 0:
raise ValueError("size must be >= 0")
self.__width = width
self.__height = height

def area(self):
return (self.__height * self.__width)
""" Module Rectangle"""class Rectangle:   """ a rectangle class that define a rectangle"""   def __init__(self, width=0, height=0):
self.height = height
self.width = width
@property
def width(self):
""" width function to retrieve the width"""
return self.__width
@width.setter
def width(self, value):
""" width function to set the value to the width
if type(value) is not int:
raise TypeError("value must be an integer")
elif value < 0:
raise ValueError("message value must be >= 0")
else:
self.__width = value
@property
def height(self):
return self.__height
@height.setter
def height(self, value):
if type(value) is not int:
raise TypeError("value must be an integer")
elif value < 0:
raise ValueError("message value must be >= 0")
else:
self.__height = value
def area(self):
return self.__width * self.__height

Differences Between Class and Instance Attributes

The advantages and drawbacks of each of them:

What does built-in class attribute __dict__ do in Python?

object.__dict__
class Sequare():
number_of_instances = 0
def __init__(self, size):
self.size = size

sequare_1 = Sequare(2)
sequare_2 = Sequare(3)

print Sequare_1.__dict__
print Sequare_2.__dict__
{'size': 2}
{'size': 3}

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store