12-28-2020, 02:11 AM
Python getattr()
Python’s built-in function returns the value of the ‘s attribute with name . If this doesn’t exist, it returns the value provided as an optional third argument. If that doesn’t exist either, it raises an . An example is which is equivalent to .
![[Image: getattr-1-1024x576.jpg]](https://blog.finxter.com/wp-content/uploads/2020/12/getattr-1-1024x576.jpg)
Usage
Learn by example! Here’s an example on how to use the built-in function.
The output of this code snippet is:
Syntax getattr()
The object has the following syntax:
Arguments |
|
The object from which the attribute value should be drawn.
|
|
The attribute name as a string.
|
|
The return value in case the attribute doesn’t exist.
Return Value |
|
Returns the value of the of instance or if non-existent.
Video getattr()
Return value from getattr()
The method returns one of the following:
Interactive Shell Exercise: Understanding getattr()
Consider the following interactive code:
https://trinket.io/embed/python/48f2b083eb
Exercise: Fix the error in the code!
But before we move on, I’m excited to present you my brand-new Python book Python One-Liners (Amazon Link).
If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!
![[Image: image-1.png]](https://blog.finxter.com/wp-content/uploads/2020/02/image-1.png)
The book is released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).
Link: https://nostarch.com/pythononeliners
Why Using getattr() Instead of Dot to Get an Attribute?
You’ve seen two alternatives to get an attribute:
Why using the getattr() function over the more concise dot syntax?
There are two main reasons:
Related Functions
Summary
Python’s built-in function returns the value of the ‘s attribute with name .
If this doesn’t exist, it returns the value provided as an optional third argument.
If that doesn’t exist either, it raises an.
An example is which is equivalent to .
I hope you enjoyed the article! To improve your Python education, you may want to join the popular free Finxter Email Academy:
Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!
Where to Go From Here?
Enough theory, let’s get some practice!
To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
Practice projects is how you sharpen your saw in coding!
Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?
Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.
Join the free webinar now!
The post Python getattr() first appeared on Finxter.
Python’s built-in
Code:
getattr(object, string)Code:
objectCode:
stringCode:
defaultCode:
AttributeErrorCode:
getattr(porsche, 'speed')Code:
porsche.speed![[Image: getattr-1-1024x576.jpg]](https://blog.finxter.com/wp-content/uploads/2020/12/getattr-1-1024x576.jpg)
Usage
Learn by example! Here’s an example on how to use the
Code:
getattr()Code:
# Define class with one attribute
class Car: def __init__(self, brand, speed): self.brand = brand self.speed = speed # Create object
porsche = Car('porsche', 100)
tesla = Car('tesla', 110) # Two alternatives to get instance attributes:
print(getattr(porsche, 'brand') + " " + str(getattr(porsche, 'speed')))
print(tesla.brand + " " + str(tesla.speed)) # Get an attribute that doesn't exist with default argument:
print(getattr(porsche, 'color', 'red'))The output of this code snippet is:
Code:
porsche 100
tesla 110
redThe
Code:
getattr()Code:
Syntax:
getattr(object, attribute[, default]) # Get object's attribute value or default if non-existentArguments |
Code:
objectThe object from which the attribute value should be drawn.
|
Code:
attributeThe attribute name as a string.
|
Code:
defaultThe return value in case the attribute doesn’t exist.
Return Value |
Code:
objectReturns the value of the
Code:
attributeCode:
objectCode:
defaultVideo getattr()
Return value from getattr()
The
Code:
getattr(object, attribute, default)- the value of the ‘sCode:
objectCode:attribute
- , if the attribute doesn’t existCode:
default
- if neither the attribute exists, norCode:
AttributeErroris provided.Code:default
Interactive Shell Exercise: Understanding getattr()
Consider the following interactive code:
https://trinket.io/embed/python/48f2b083eb
Exercise: Fix the error in the code!
But before we move on, I’m excited to present you my brand-new Python book Python One-Liners (Amazon Link).
If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!
![[Image: image-1.png]](https://blog.finxter.com/wp-content/uploads/2020/02/image-1.png)
The book is released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).
Link: https://nostarch.com/pythononeliners
Why Using getattr() Instead of Dot to Get an Attribute?
You’ve seen two alternatives to get an attribute:
- Code:
getattr(object, attribute_str)
- Code:
object.attribute
Why using the getattr() function over the more concise dot syntax?
There are two main reasons:
- provides a default value in case the attribute doesn’t exist whereas the dot syntax throws an error.Code:
getattr()
- allows to dynamically access the attribute with the string instead of the name. For example, you may obtain the string as a user input, in which case, you cannot use the dot syntaxCode:
getattr()becauseCode:object.attributeis a string, not a name.Code:attribute
Related Functions
- The function returns the value of an attribute.Code:
setattr()
- The function checks if an attribute exists.Code:
hasattr()
- The function deletes an existing attribute.Code:
delattr()
Summary
Python’s built-in
Code:
getattr(object, string)Code:
objectCode:
stringCode:
# Define class with one attribute
class Car: def __init__(self, brand, speed): self.brand = brand self.speed = speed porsche = Car('porsche', 100)
print(getattr(porsche, 'brand') + " " + str(getattr(porsche, 'speed')))
# porsche 100If this doesn’t exist, it returns the value provided as an optional third
Code:
defaultCode:
print(getattr(porsche, 'color', 'red'))
# redIf that doesn’t exist either, it raises an
Code:
AttributeErrorCode:
print(getattr(porsche, 'color')) '''
Traceback (most recent call last): File "C:\Users\xcent\Desktop\Finxter\Blog\HowToConvertBooleanToStringPython\code.py", line 12, in <module> print(getattr(porsche, 'color'))
AttributeError: 'Car' object has no attribute 'color' '''An example is
Code:
getattr(porsche, 'speed')Code:
porsche.speedCode:
print(getattr(porsche, 'speed'))
print(porsche.speed)
# Both print attribute value: 100I hope you enjoyed the article! To improve your Python education, you may want to join the popular free Finxter Email Academy:
Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!
Where to Go From Here?
Enough theory, let’s get some practice!
To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
Practice projects is how you sharpen your saw in coding!
Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?
Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.
Join the free webinar now!
The post Python getattr() first appeared on Finxter.

