Answers for "@property in python"

11

@property in python

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

    @property
    def name(self):
        print('Getting name')
        return self._name

    @name.setter
    def name(self, value):
        print('Setting name to ' + value)
        self._name = value

    @name.deleter
    def name(self):
        print('Deleting name')
        del self._name

p = Person('Adam')
print('The name is:', p.name)
p.name = 'John'
del p.name
Posted by: Guest on December-07-2020
2

python property

class Number:

    def __init__(self, number):
        self.__number = number

    def get_number(self):
        print("Getting...")
        return self.__number

    def set_number(self, number):
        print("Setting...")
        self.__number = number
        
    def del_number(self):
        print("Deleting...")
        del self.__number

    nb = property()
    nb = nb.getter(get_number)
    nb = nb.setter(set_number)
    nb = nb.deleter(del_number)

n = Number(42)

print(n.nb)
n.nb = 69
print(n.nb)
del n.nb

# Getting...
# 42        
# Setting...
# Getting...
# 69
# Deleting...
Posted by: Guest on August-31-2021
2

@property in python

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

    def get_name(self):
        print('Getting name')
        return self._name

    def set_name(self, value):
        print('Setting name to ' + value)
        self._name = value

    def del_name(self):
        print('Deleting name')
        del self._name

    # Set property to use get_name, set_name
    # and del_name methods
    name = property(get_name, set_name, del_name, 'Name property')

p = Person('Adam')
print(p.name)
p.name = 'John'
del p.name
Posted by: Guest on December-07-2020
-1

@property in python

Getting name
The name is: Adam
Setting name to John
Deleting name
Posted by: Guest on December-07-2020

Python Answers by Framework

Browse Popular Code Answers by Language