Do you know how to make a #Python class method act like an attribute?
You can do that by turning the method into a `property`
Learn how in this thread!
๐งต๐๐
The first step is to look at a regular #Python class.
The following `Person` class has a method called `full_name()`. To get the full name of the `Person`, you must call `full_name()`
Wouldn't it be nice if you could just use dot notation instead of calling it?
In #Python, you can turn the method into a `property` using the `@property` decorator
Once you do that, you can then use dot notation to access the `full_name()` method as if it were an instance attribute!
What if you want to set the property to a new value though? I mean, in a normal #Python class, the attributes can be set by doing something like `p.first_name = "Jane"`
If you try that with the `full_name` property you will get an `AttributeError`!
To make a property settable, you need to add a new function with a special decorator.
In this case, you have the `full_name()` decorated with `@property`
To add a setter, you need to create a SECOND `full_name()` method and decorate it with `@full_name.setter`
Let's look at another example! Here is a regular class that has a getter and setter function:
๐ get_fee()
๐ set_fee()
When you create a class with getters and setters, you kind of miss out on the power of Python because you can't use dot notation here
You can update the class to add a `property` by using the `property()` function.
The following is kind of a sneaky way to turn those two methods into a property without adding the `@property` decorator
However, in #Python, it is better to be explicit so here is the class rewrote with the `@property` applied
Now you'll be able to get and set the values using regular dot notation
The code for most of the examples here come from one of my tutorials @mousevspython
Want to create a copy of a #Python list? Use Python's `copy()` method!
Note: Watch out if your list contains lists of dictionaries. In those cases, you might be better off using copy.deepcopy()
But be careful! If your list contains a mutable object, like another list or a dictionary, you may encounter some unexpected behavior.
In the following example, you `copy()` the list. Then you modify the nested dictionary in the copy, but that also changes the original list!
You can fix this behavior by using Python's `copy` module. It provides a deepcopy() function that you can use which will make a deep copy of the ENTIRE list!