In Python, we often use print 🖨️ statements with parentheses to output values. However, there's a creative way to print values without using braces by leveraging properties in a custom class. Let's dive into how we can achieve this using a custom class design. 🔍
## Custom Class Design 🛠️
Here’s a simple class that allows printing values without the need for parentheses:
```python
class disp_cls():
def __init__(self):
return
@property
def out(self):
return self
@out.setter
def out(self, other):
print(other)
return
disp = disp_cls()
disp.out = 1, 2, 3
```
### Breakdown 🧩
1. **Class Definition**: We define a class called `disp_cls`.
2. **Constructor**: The `__init__` method initializes the class but doesn't do anything special here.
3. **Property Getter**: The `out` property method returns the instance itself (`self`). This is necessary for the property to work correctly.
4. **Property Setter**: The `out` setter method is where the magic happens. It takes the value being assigned to `disp.out` (in this case, `1, 2, 3`) and prints it.
5. **Usage**: We create an instance of `disp_cls` called `disp` and assign a tuple `1, 2, 3` to `disp.out`. This triggers the setter method, which prints the tuple.
## How It Works 🚀
When we assign `disp.out = 1, 2, 3`, the following steps occur:
- The assignment triggers the `out` setter method.
- The setter method prints the assigned value (`1, 2, 3`).
This allows us to print values without explicitly calling the `print` function, thus avoiding the use of parentheses for the print statement. 🎉
## Conclusion 🏁
By using properties in a custom class, we can creatively bypass the need for parentheses when printing values in Python. This approach demonstrates the flexibility and power of Python's property decorators and can be a fun way to streamline your code. Give it a try and see how it works for you! Happy coding! 💻😊
interactive example
https://colab.research.google.com/drive/1MmkC9meGmONcEFwXimQKC8F0Q4TrNZWs
Comments
Post a Comment