Register Login

Attributes in Python

Updated Apr 19, 2022

Any object-oriented programming language has characteristic properties and behaviour. Characteristic properties in any language are the same as attributes in python. All the attributes of a python class can be excess with the function dir() and vars().

Program:

class attr:
    x = "class attribute"
    def __init__(self,y):
        self.y = y
print("Output:")
obj = attr("instance attribute")
print(attr.x)
print(obj.y)

Explanation:

Here, we create variable x as a string which is a class attribute and a y string which is an instance attribute. At last print the values of both the variables.

Types of attributes:

Attributes follow two types:

  1. Class attributes
  2. Instance attributes

Class attributes:

Attributes that are defined outside the method in the python class object are known as class attributes. These attributes can be accessed by class and instance objects. They belong to the class.

Syntax:

class name:
<class attributes>
<class attributes> 

 

Program:

class attr:
    x="class attribute” 
print("Output:")
obj=attr()
print(obj.x)

Explanation:

Here, we create a variable x next to the class attr. Variable x is a class attribute. Create an inject obj of class attr and by the instance of class print the value of x.

Instance attributes:

Instance attributes are the attributes that are defined inside __init__ method. These attributes can be accessed by an instance of the class. They belong to instances of objects.

Syntax:

class name:
	def __init__(self, ..)
        <instance attributes>
        <instance attributes> 

Program:

class attr:
    x = "class attribute"
    def __init__(self,y):
        self.y = y   
print("Output:")
obj = attr("instance attribute")
print(obj.y)

Explanation:

Here, we create a variable y inside __init__ method .y is an instance attribute. Create an obj object f class and print the value of y.

Uses of class attributes:

Class attributes are used in many cases. Some of the use cases areas:

  1. To create a constant value variable
  2.  Listing object/data across all instances
  3. To give a default value

Class attributes are initialized across all instances of the class. So, class attributes can be used to create constant value variables in the class. These variables can be used in the method. So, attributes take low space in memory and less time to initialize.

Program:

class pro:
    pi = 3.14
    def __init__(self,r):
        self.r = r
    def area(self):
        print("A =")
        print(2 * self.pi * self.r)
        
    print("Output:")
obj=pro(10)
print(obj. area())

Explanation:

Here, we create a variable pi which takes a constant value. Pi is a class attribute. Create a method area that calculates the area. Create an object of the class and print the area of a circle.

In case we want to excess some properties of all the instances of the class. It is very time-consuming to excess properties by calling each object.  So, All the instances can be arranged in a single variable by the use of class attributes.

Program:

class first:
    ids = []
    def __init__(self, stuid, name):
        self.stuid = stuid
        self.name = name
        first.ids.append(stuid)
print("Output:")
s1 = first(1,"a")
s1= first(2,"b")
s1= first(3,"c")
print(first.ids)

Explanation:

Here, we create a list of ids as class attributes which are used inside the init method to append all ids of students inside the list of all the instances of the class. We create three objects for the class. At last print the list.

With class attributes, a default value can be provided to attribute in the custom class. By excessing the attributes by class or instance value can be changed.

Program:

class vote:
    age = 18
    c = 0
    def __init__(self, age, name):
        self.age = age
        self.name = name
    def votting(self):
        if (self.age < vote.age):
            return
        vote.c += 1
        
print("Output:")
p=vote(19, "a")
p.votting()
print(vote.c)

Explanation:

Here, we create a class attribute age which is used inside the votting method to compare the age of instance of the class.

Class to instance attribute:

  1. A class attribute can be changed to an instance attribute by changing the value of the class attribute with the instance of the class.
  2. This is not in the case where a class attribute is a mutable object such as a list etc.

Program:

class pro:
    x="a"
    def __init__(self, y, z):
        self.y = y
        self.z = z
    def fun(self):
        print("method called")
    print("Output:")
obj=pro("b", "c")
obj2=pro("b", "c")
obj.x="instance var a"
print(obj.x)
print(pro.x)
print(obj2.x)
print("---------")
print(dir(obj))

Explanation:

Here we create a variable x as class attributes. The value of x is changed by the obj (instance of the class). Print the value of x by obj, class pro and another object obj2. Check the attributes of obj by printing the dir of obj.

Namespaces in attributes:

  1. A namespace is a dictionary in python that stores keys as objects of class and values as attributes. A namespace is divided in this case into two parts object namespace and class namespace.
  2. When a class instance accesses any attribute, it first searches into the object namespace then the class namespace. Instance attributes take preference over class attributes. In programming cost of accessing class attributes by the instance of the class will be time-consuming.
  3. When a class accesses any attribute, it is searched in the class attribute and otherwise throws an error.

Function and attributes:  

  1. In python, functions are treated as attributes of the class. All the static, class, instance methods are attributes that belong to the class.
  2. Static and class methods are associated with class whereas the instance method is associated with the instance of the class.
  3. In python instance methods can also be invoked by the class itself by passing instances of an object in the method. It saves memory in the python program.

Program:

class pro:
    x="a"
    def __init__(self, y, z):
        self.y = y
        self.z = z
    @classmethod
    def funclmethod(cls, f):
        y = f["y"]
        z=f["z"]
        print("classmethod called")
        return cls(y, z)
    @staticmethod
    def funstmethod():
        print("staticmethod called")
    
    def funinstmethod(self):
        print("instance method called")
print("Output:")
obj=pro("b", "c")
obj.funinstmethod()
pro.funinstmethod(obj)

Explanation:

Here, we create three functions funclmethod, funstmethod, funinstmethod with decorate @classmethod, @staticmethod.Create an object of class pro as obj and call the instance method funinstmethod.Secondly, Call the instance method by passing the obj instance of class.

Properties vs. Attributes:

In python, properties are completely different from attributes. Properties are the method with @properties decorator. These are used to access private attributes of a class and act as getter-setter functions in a python class.

Program:

class pro:
    _z="a"
    def __init__(self,x):
        self.x=x
    @property
    def fun(self):
        return self.x
    @fun.setter
    def fun(self, nx):
        self.x = nx
print("Output:")
y = pro(" Call property function.")
print(y.fun)
y.fun = "Value change"
print(y.fun)

Explanation:

Here, we create methods fun with decorator @property, @fun.setter which are used to get and set the values of variable x.

Conclusion:

We hope this article has given you all a clear idea about the Attributes, types of attributes (class attribute and instance attribute), use of class attributes, class to instance attribute, the namespace in attributes, functions, and attributes, properties vs. attributes.

For object-oriented programmers in Python, dealing with class attributes is essential to know. Therefore, it is highly recommended to use python attributes while programming because it consumes less memory and followed an object-oriented programming approach.


×