property in python class code example
Example 1: @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
Example 2: class attributes in python
class MyClass:
class_attr = 0
def __init__(self, inst):
self.instance_attr = inst
obj = MyClass(1)
print(obj.class_attr)
print(obj.instance_attr)
print(MyClass.class_attr)
print(MyClass.instance_attr)
Example 3: @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
name = property(get_name, set_name, del_name, 'Name property')
p = Person('Adam')
print(p.name)
p.name = 'John'
del p.name