![]() |
|
[Tut] Python getattr() - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Python getattr() (/thread-98964.html) |
[Tut] Python getattr() - xSicKxBot - 12-28-2020 Python getattr() Python’s built-in Code: getattr(object, string)Code: objectCode: stringCode: defaultCode: AttributeErrorCode: getattr(porsche, 'speed')Code: porsche.speed![]() 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)
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! ![]() 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 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. |