Add attribute to python class

Функция setattr() в Python: создание атрибута объекта

Мы знаем, что можно присвоить значение переменной класса через конструктор и объектную функцию. Но помимо этого есть еще один альтернативный способ: метод setattr().

Что такое функция setattr() в Python?

Функция setattr() в Python — это встроенная функция, которая создает и устанавливает значение данного атрибута объекта класса. Метод setattr() может присвоить None любому атрибуту объекта и может использоваться для инициализации нового атрибута объекта.

Синтаксис

Аргументы

Функция использует следующие три параметра:

  1. object: это объект, чей атрибут должен быть установлен или изменен.
  2. name: это строка, содержащая имя устанавливаемого атрибута.
  3. value: значение, которое должно быть установлено.

Возвращаемое значение

Функция ничего не возвращает. Таким образом, возвращаемое значение равно None.

Программа, показывающая, как работает setattr()

В приведенном выше примере мы видим, что мы изменили значение номера рулона с 24 на 20 с помощью метода setattr(), и после этого, когда мы его вызываем, мы можем увидеть измененное значение.

Когда атрибут имени не найден и для него установлено значение «None»

В приведенном выше примере мы установили значение атрибута name равным None, поэтому мы можем узнать, что мы также можем присвоить значение None.

Читайте также:  Методы tolowercase и touppercase javascript

С другой стороны, как мы видим, в классе Student нет атрибута section, но мы использовали его в setattr().

В данном случае произошло следующее: функция setattr() сама создает новый атрибут, если этот атрибут отсутствует в классе, а затем присваивает ему заданное значение.

Python setattr() с пользовательским вводом

Мы используем функцию Python input(), чтобы получить ввод от пользователя и передать это значение функции setattr().

Источник

Add attribute to python class

Last updated: Feb 22, 2023
Reading time · 3 min

banner

# Table of Contents

# Add attributes to an Object in Python

Use the setattr() function to add attributes to an object, e.g. setattr(obj, ‘name’, ‘value’) .

The setattr function takes an object, the name of the attribute and its value as arguments and adds the specified attribute to the object.

Copied!
class Employee(): def __init__(self, name): self.name = name emp1 = Employee('bobby') setattr(emp1, 'salary', 100) setattr(emp1, 'age', 30) print(getattr(emp1, 'salary')) # 👉️ 100 print(getattr(emp1, 'age')) # 👉️ 30 print(getattr(emp1, 'name')) # 👉️ bobby

We instantiated the Employee() class and used the setattr() function to add attributes to the object.

The setattr function adds an attribute to an object.

The function takes the following 3 arguments:

Name Description
object the object to which the attribute is added
name the name of the attribute
value the value of the attribute

The name string may be an existing or a new attribute.

If you need to create a generic object, use the pass statement in a class.

Copied!
class GenericClass(): pass obj1 = GenericClass() setattr(obj1, 'salary', 100) setattr(obj1, 'age', 30) print(getattr(obj1, 'salary')) # 👉️ 100 print(getattr(obj1, 'age')) # 👉️ 30

The pass statement does nothing and is used when a statement is required syntactically but the program requires no action.

Make sure your class does not extend from the built-in object class.

The object class doesn’t have a __dict__ attribute, therefore we can’t assign attributes to an instance of the class.

# Add attribute to an Object using dot notation

You can also use dot notation to add an attribute to an object.

Copied!
class GenericClass(): pass obj1 = GenericClass() obj1.salary = 100 obj1.age = 30 print(getattr(obj1, 'salary')) # 👉️ 100 print(getattr(obj1, 'age')) # 👉️ 30 print(obj1.salary) # 👉️ 100 print(obj1.age) # 👉️ 30

Using dot notation is equivalent to using the setattr() method.

However, when using dot notation, you might get linting warnings for defining attributes outside of the _ _ init _ _ () method.

# Add multiple attributes to an object using a for loop

You can use a for loop if you need to add multiple attributes to an object.

Copied!
class GenericClass(): pass my_dict = 'name': 'bobbyhadz', 'age': 30> obj1 = GenericClass() for key, value in my_dict.items(): setattr(obj1, key, value) print(getattr(obj1, 'name')) # 👉️ bobbyhadz print(getattr(obj1, 'age')) # 👉️ 30

We used a for loop to iterate over a dictionary’s items and added the key-value pairs as attributes to the object.

If you have to use the setattr method from within a class method, you would pass self as the first argument.

Copied!
class GenericClass(): def __init__(self, dictionary): for key, value in dictionary.items(): setattr(self, key, value) my_dict = 'name': 'bobbyhadz', 'age': 30> obj1 = GenericClass(my_dict) print(getattr(obj1, 'name')) # 👉️ bobbyhadz print(getattr(obj1, 'age')) # 👉️ 30

You can also use the SimpleNamespace class if you need to create a generic object to which you can add attributes.

# Add attributes to an Object using SimpleNamespace()

This is a two-step process:

  1. Use the SimpleNamespace class to create an object.
  2. Use the setattr() function to add attributes to the object.
Copied!
from types import SimpleNamespace obj1 = SimpleNamespace() setattr(obj1, 'salary', 100) setattr(obj1, 'language', 'Python') print(getattr(obj1, 'salary')) # 👉️ 100 print(getattr(obj1, 'language')) # 👉️ Python print(obj1) # 👉️ namespace(salary=100, language='Python')

The SimpleNamespace class is a subclass of object and provides attribute access to its namespace.

We can’t add attributes to instances of the built-in object class, however, we can attributes to instances of the SimpleNamespace class.

The class can also be initialized with keyword arguments.

Copied!
from types import SimpleNamespace obj1 = SimpleNamespace(name='bobby', age=30) setattr(obj1, 'salary', 100) setattr(obj1, 'language', 'Python') print(getattr(obj1, 'salary')) # 👉️ 100 print(getattr(obj1, 'language')) # 👉️ Python print(getattr(obj1, 'name')) # 👉️ bobby print(getattr(obj1, 'age')) # 👉️ 30 # 👇️ namespace(name='bobby', age=30, salary=100, language='Python') print(obj1)

The SimpleNamespace class is quite convenient when you need to create a blank object to which you can add attributes.

Attributes cannot be added to the built-in object class, so the SimpleNamespace should be your preferred approach.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Adding Attributes to a Python Class

Austin Cepalia

In this video, we start building our Dog class and fill it out with attributes.

We can instantiate our Dog class like this

We can access the instance attributes with dot notation.

malcolmgandrews on Sept. 30, 2019

I don’t want to be a pedant but a Mouse is a Mammal.

richardojeda1985 on Oct. 24, 2019

ok what if you are working in a class with user input? how would you call the str method??

Austin Cepalia RP Team on Oct. 27, 2019

I’m not exactly sure what you mean by “working in a class with user input.” There are a few approaches you can take if you need user input. The first one is to instantiate the class with the input already stored in a variable like this:

class Person: def __init__(self, name): self.name = name name = input('enter your name: ') person = Person(name) 

Or you could ask for user input in the __init__ method like this:

class Person: def __init__(self): self.name = input('enter your name: ') person = Person() 

str() is used to convert a value into a string. input() returns a string, so I’m not sure why you would need to call that. If you’re talking about getting a string representation of the object instantiated from your class, you can do something like this:

class Person: def __init__(self, name): self.name = name def __str__(self): return 'this object has name ' + self.name name = input('enter your name: ') person = Person(name) print(person) 

This is beyond the scope of this course, but str defines the string representation of an object (This is similar to overriding ToString() in other languages). When we pass the person object to the print() function, it calls str under-the-hood and prints the string representation of the object. You can learn more about that here Let me know if you have any other questions!

Why do you use <> and format instead of just printing the attributes?

Austin Cepalia RP Team on Nov. 5, 2019

@kwf777 This was my first course. I was under the impression I needed to follow the article exactly, which used .format() because it’s a bit older. I use fstrings in all my courses now 🙂

Oleksii Potapenko on Nov. 13, 2019

At 5:35 output is changing without any run code.

sideproject8 on Dec. 17, 2019

Please re-record this with the new f-strings. Might be silly to ask but as someone who is really trying to learn python, this small issue just keeps messing me up and takes me out of the flow of your courses, when other videos on here use f-strings. Please and thank you.

mnemonic6502 on Jan. 18, 2020

Regarding species not being printed second time around after species was changed to ‘mouse’ was useful to highlight, but took reviewing. Could have been made clearer by saying something like it’s not printed out on right because yada yada etc (rather than assuming the learner knew the lack of output as a parallel from your technical explanation).

Hi Austin,for clarification that class attributes is a permenant attributes compare instance attributes that can modify even outside of class code blocks.

Ricardo on April 11, 2020

A rose by any other name smells as sweet … I’m a Java person, but not hugely “formally” trained. Thus, if the high keepers of the Java flame make a distinction between class attributes and instance attributes, (properties), I don’t remember. I simply define class vars in Java and give them default values, or leave them null and give them values during construction – the practical results always seem the same. (I’m bypassing visibility, protection, etc.) Here in Python the class and instance var terminology functionally doesn’t seem to make a lot of difference either, though I do see the conceptual difference. What I’m trying to express is that as soon as you say

__init__(self,myinstanceattr) self.myinstanceattr 

then “myinstanceattr” becomes an inextricable part of every self example of the class just as a class attribute would be – the only difference is that “classattr” would have a pre-assigned default value (which I find can even be None). However, the instance attributes are “required” to be assigned values during the creation of the class instance (haven’t seen an automatic default init yet, though can define an equivalent). Once you have an instance, both the class and instance attributes can be accessed and modified using the “.” operator. So, long short: I’ll be waiting to see in the next vids if there’s any deep down difference behind “class” vs. “instance” vars, like speed of access or storage locations or something.

Very good presentations. Clean, well thought, great delivery. Thespian? Experienced teacher? Little things make me suspect you’re a C++ or Java guy also, either now or in your beginnings.

Austin Cepalia RP Team on April 14, 2020

@Zarata Not thespian, but I do have a lot of experience teaching. Particularly with kids who don’t respond well to boring teachers. You were close with the languages too, my background is primarily C# and .NET 🙂

So in essence everything in python we’ve been learning is oop? Is that why certain built in functions work with str.object and not with tuple.object?

Thomas J Foolery on June 22, 2020

How does Python enforce encapsulation?

Источник

Оцените статью