Python property() Built in Function

The property() function is used to create and return a property object that has a getter, a setter, and a deleter method. The syntax of this function is:

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

The fget parameter is optional and specifies a function to get the value of the attribute. The fset parameter is optional and specifies a function to set the value of the attribute. The fdel parameter is optional and specifies a function to delete the attribute. The doc parameter is optional and specifies a string that serves as the documentation for the attribute.

The property() function can be used as a decorator or as a normal function. Here are some examples of using the property() function in Python:

To create a read-only property using @property decorator:

class Person:
    def __init__(self, name):
        self._name = name
# private attribute

    @property
    def name(self):
# getter method
        return self._name

p = Person("Alice")

print(p.name) # prints Alice
p.name = "Bob" # raises AttributeError

To create a read-write property using @property decorator and setter method:

class Person:
    def __init__(self, name):
        self._name = name
# private attribute

    @property
    def name(self):
# getter method
        return self._name

    @name.setter
    def name(self, value):
# setter method
        if not isinstance(value, str):
            raise TypeError("Name must be a string")
        self._name = value


p = Person("Alice")
print(p.name)
# prints Alice
p.name = "Bob" # sets name to Bob
print(p.name) # prints Bob
p.name = 42 # raises TypeError

To create a property using property() function as a normal function:

class Person:
    def __init__(self, name):
        self._name = name
# private attribute

    def get_name(self): # getter method
        return self._name


    def set_name(self, value): # setter method
        if not isinstance(value, str):
            raise TypeError("Name must be a string")
        self._name = value


    def del_name(self): # deleter method
        del self._name


    name = property(get_name, set_name, del_name) # creates property object

p = Person("Alice")
print(p.name)
# prints Alice
p.name = "Bob" # sets name to Bob
print(p.name) # prints Bob
del p.name

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions