setattr()

setattr(object, attribute,value) adds or updates the value of attribute of the input object
object (required ) , input object for which the attribute will be updated or added.
attribute ( required ), attribute to be updated / added.
value ( required ), new value of the attribute.

Read more on Class Object and Attributes
Adding new attribute
class Animal():

     #class attributes
    species='carnivores'

     #instance attributes
    def __init__(self1,name1,age):
        self1.name= name1
        self1.age=age

#instantiate the Animal  class
tiger=Animal("Ronald",5)      # object created
setattr(tiger,'height',3.5)   # new attribute added
print(tiger.height)           # showing value of new attribute
Output
3.5
In above code we created an object tiger. By using setattr() we added one more attibute height. The last line will print the value of new attribute.

Updating value of the attribute

We will change the value of one attribute.
class Animal():

     #class attributes
    species='carnivores'

     #instance attributes
    def __init__(self1,name1,age):
        self1.name= name1
        self1.age=age
        

 #instantiate the Animal  class
tiger=Animal("Ronald",5) 
setattr(tiger,'age',6)
print("New age : ",tiger.age)
Output
New age :  6

Setting the value to None

tiger=Animal("Ronald",5) 
setattr(tiger,'age',None)
print("New age : ",tiger.age)
Output
New age :  None

All Built in Functions in Python delattr() getattr() hasattr()

Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer