Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python property() — What You Always Wanted to Know But Never Dared to Ask

#1
Python property() — What You Always Wanted to Know But Never Dared to Ask

Object-orientation is great way to encapsulate data in your application. This minimizes complexity and adheres to good software engineering principles.

However, attributes in Python can be easily accessed from the outside—they’re not really encapsulated. That’s one of the reason the property() built-in function exists: it allows you to truly encapsulate data with the means of private attributes that you can access via getter and setter functions from the outside.

Python property()https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w" sizes="(max-width: 768px) 100vw, 768px" />

Python’s built-in property() function creates and returns a new property attribute that should be private, i.e., only accessible via defined functions. As arguments, you pass three functions to get, set, and delete the attribute value—as well as the fourth docstring argument. All four arguments are None per default.

Here’s the formal syntax and argument list of the property() function:

property(fget=None, fset=None, fdel=None, doc=None)

Arguments fget Callable function object for getting an attribute value. Returns the attribute value.
fset Callable function object for setting an attribute value. No return value required.
fdel Callable function object for deleting an attribute value. No return value required.
doc String describing the documentation of the attribute.
Return Value property Returns new object of class property that allows you to access the property from the outside via defined getter and setter methods.

Python property() — Usage Examples


Learn by example! In the following, we’re going to explore an example of why and how to use the property() built-in function.

Have a look at this simple Car class for which we create a “secret” _owner attribute—note the prefixed underscore to discourage external access:

class Car: def __init__(self): self._owner = None def get_owner(self): return self._owner def set_owner(self, name): self._owner = name def delete_owner(self): del self._owner porsche = Car()
porsche.set_owner('Chris')
print(porsche.get_owner())
# Chris

The owner attribute has a getter function, a setter function, and a delete function that removes the attribute.

This follows the guidelines of object orientation to allow external access of object attributes only via functions rather than directly via porsche._owner. However, using complicated getter and setter function names can be a pain. That’s why you can also add an additional line using the property() function to make _owner a property rather than just an attribute:

class Car: def __init__(self): self._owner = None def get_owner(self): return self._owner def set_owner(self, name): self._owner = name def delete_owner(self): del self._owner # Creates a property: Car.owner owner = property(get_owner, set_owner, delete_owner, 'Owner of the car') porsche = Car()
porsche.owner = 'Chris'
print(porsche.owner)
# Chris

This greatly facilitates access of the attribute. Instead of calling the clunky porsche._owner or even porsche.get_owner(), you can now call porsche.owner as if owner was an attribute. Python then internally calls the defined getter and setter functions to modify, access, or delete the attribute _owner.

Python property() — Video





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 was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

Link: https://nostarch.com/pythononeliners

Python property() — Interactive Code Exercise


Let’s have a look at a practical exercise:

Exercise: Replace both occurrences of ??? with some code to make you the owner of the Porsche!


Summary


Object-orientation is great way to encapsulate data in your application. This minimizes complexity and adheres to good software engineering principles.

However, attributes in Python can be easily accessed from the outside—they’re not really encapsulated. That’s one of the reason the property() built-in function exists: it allows you to truly encapsulate data with the means of private attributes that you can access via getter and setter functions from the outside.

Python’s built-in property() function creates and returns a new property attribute that should be private, i.e., only accessible via defined functions. As arguments, you pass three functions to get, set, and delete the attribute value—as well as the fourth docstring argument. All four arguments are None per default.


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 property() — What You Always Wanted to Know But Never Dared to Ask first appeared on Finxter.



https://www.sickgaming.net/blog/2021/02/...ed-to-ask/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] Python Get Milliseconds xSicKxBot 0 41 02-19-2021, 08:28 AM
Last Post: xSicKxBot
  [Tut] Python str() Function xSicKxBot 0 39 02-14-2021, 06:05 AM
Last Post: xSicKxBot
  [Tut] Python issubclass() xSicKxBot 0 44 02-12-2021, 10:40 AM
Last Post: xSicKxBot
  [Tut] Python int() Function xSicKxBot 0 48 02-04-2021, 08:21 PM
Last Post: xSicKxBot
  [Tut] How To Cut A String In Python? xSicKxBot 0 37 02-01-2021, 04:09 PM
Last Post: xSicKxBot
  [Tut] Python filter() xSicKxBot 0 58 02-01-2021, 03:25 AM
Last Post: xSicKxBot
  [Tut] Python help() xSicKxBot 0 43 01-22-2021, 01:02 AM
Last Post: xSicKxBot
  [Tut] Python globals() xSicKxBot 0 46 01-19-2021, 04:16 AM
Last Post: xSicKxBot
  [Tut] Python getattr() xSicKxBot 0 54 12-28-2020, 05:11 AM
Last Post: xSicKxBot
  [Tut] Python delattr() xSicKxBot 0 56 12-26-2020, 12:06 AM
Last Post: xSicKxBot

Forum Jump:

[-]
Active Threads
News - Don’t forget to take the GDC 2021...
Last Post: xSicKxBot
Today 02:42 AM
» Replies: 0
» Views: 0
How to get free CS - GO Skins!
Last Post: Augustgeows
Today 01:30 AM
» Replies: 13
» Views: 12624
News - A New Patch For Bloodstained: Rit...
Last Post: xSicKxBot
Yesterday 09:39 PM
» Replies: 0
» Views: 3
News - Best Mario Day Deals: Super Mario...
Last Post: xSicKxBot
Yesterday 09:39 PM
» Replies: 0
» Views: 5
[Tut] How To Run Multiple Python Version...
Last Post: xSicKxBot
Yesterday 03:30 PM
» Replies: 0
» Views: 7
(Indie Deal) 3dSen PC & VR, Human Fall F...
Last Post: xSicKxBot
Yesterday 03:30 PM
» Replies: 0
» Views: 5
Unreal Engine Coming To A Cloud Near You
Last Post: xSicKxBot
Yesterday 09:39 AM
» Replies: 0
» Views: 5
[Tut] Python iter() — A Simple Illustrat...
Last Post: xSicKxBot
Yesterday 12:28 AM
» Replies: 0
» Views: 7
(Indie Deal) Warhammer: Chaosbane, WRC 9...
Last Post: xSicKxBot
Yesterday 12:28 AM
» Replies: 0
» Views: 6
News - Introducing the Bungie Tech Blog
Last Post: xSicKxBot
Yesterday 12:27 AM
» Replies: 0
» Views: 6

[-]
Twitter

[-]
Sponsored
Get the Deal of the Week at RefurBees.com

Copyright © SickGaming.net 2012-2020