Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python setattr() Function



ThePython setattr() function allows us to set a new value to an attribute of the specified object. It is used for creating a new attribute and setting values to it. It is one of thebuilt-in functions and does not require any module to use this.

Syntax

Following is the syntax of the Pythonsetattr() function −

setattr(object, attribute, value)

Parameters

The Pythonsetattr() function accepts the following parameters −

  • object − This parameter represents an object.

  • attribute − It represents the attribute name.

  • value − It specifies the value to be set.

Return Value

The Pythonsetattr() function returns None value.

setattr() Function Examples

Practice the following examples to understand the use ofsetattr() function in Python:

Example: Use of setattr() Function

The following example shows the usage of Python setattr() function. Here, we are creating a class and setting a new attribute of that class.

class OrgName:   def __init__(self, name):      self.name = namenameObj = OrgName("TutorialsPoint")setattr(nameObj, "location", "Hyderabad")  print("Location is set to:", nameObj.location)

When we run above program, it produces following result −

Location is set to: Hyderabad

Example: Modify Attribute's Value Using setattr() Function

The setattr() function can also be used to modify the value of existingattributes. In the code below, we are modifying the previously set value of the location attribute with the new one.

class TutorialsPoint:   def __init__(self, location):      self.location = locationlocationObj = TutorialsPoint("Hyderabad")print("Before modifying location is set to:", locationObj.location) setattr(locationObj, "location", "Noida")  print("After modifying location is set to:", locationObj.location)

Following is an output of the above code −

Before modifying location is set to: HyderabadAfter modifying location is set to: Noida

Example: Add Class Methods Dynamically Using setattr() Function

With the help of setattr() function, we can addclass methods dynamically. In the following code, we have defined a method named "employee" and adding the defined method to the specified class.

class TutorialsPoint:   pass    def employee():   return "Present"employeeObj = TutorialsPoint()setattr(employeeObj, "isPresent", employee)  print("Status of employee is set to:", employeeObj.isPresent())

Output of the above code is as follows −

Status of employee is set to: Present
python_built_in_functions.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp