Python-b05-Property Decorators

This article shows the examples of in python

email does not change when first changes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Employee:
raise_amount = 2.04

def __init__(self, first, last):
self.first = first
self.last = last
self.email = first + '.' + last + '@company.com'

def fullname(self):
return '{} {}'.format(self.first, self.last)


emp_1 = Employee('Bob', 'Gobdo')

emp_1.first = 'Jim'

print(emp_1.first) # Jim
print(emp_1.email) # Bob.Gobdo@company.com
print(emp_1.fullname()) # Jim Gobdo

email move into method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Employee:
raise_amount = 2.04

def __init__(self, first, last):
self.first = first
self.last = last

def email(self):
return '{}.{}@company.com'.format(self.first, self.last)

def fullname(self):
return '{} {}'.format(self.first, self.last)


emp_1 = Employee('Bob', 'Gobdo')

emp_1.first = 'Jim'

print(emp_1.first) # Jim
print(emp_1.email()) # Jim.Gobdo@company.com
print(emp_1.fullname()) # Jim Gobdo

add @property on method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Employee:
raise_amount = 2.04

def __init__(self, first, last):
self.first = first
self.last = last

@property
def email(self):
return '{}.{}@company.com'.format(self.first, self.last)

@property
def fullname(self):
return '{} {}'.format(self.first, self.last)


emp_1 = Employee('Bob', 'Gobdo')

emp_1.first = 'Jim'

print(emp_1.first) # Jim
print(emp_1.email) # Jim.Gobdo@company.com
print(emp_1.fullname) # Jim Gobdo

setter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Employee:
raise_amount = 2.04

def __init__(self, first, last):
self.first = first
self.last = last

@property
def email(self):
return '{}.{}@company.com'.format(self.first, self.last)

@property
def fullname(self):
return '{} {}'.format(self.first, self.last)

@fullname.setter
def fullname(self, name):
first, last = name.split(' ')
self.first = first
self.last = last

emp_1 = Employee('Bob', 'Gobdo')

emp_1.fullname = 'John Smith'

print(emp_1.first) # John
print(emp_1.email) # John.Smith@company.com
print(emp_1.fullname) # John Smith

deleter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Employee:
raise_amount = 2.04

def __init__(self, first, last):
self.first = first
self.last = last

@property
def email(self):
return '{}.{}@company.com'.format(self.first, self.last)

@property
def fullname(self):
return '{} {}'.format(self.first, self.last)

@fullname.setter
def fullname(self, name):
first, last = name.split(' ')
self.first = first
self.last = last

@fullname.deleter
def fullname(self):
print('Delete name')
self.first = None
self.last = None

emp_1 = Employee('Bob', 'Gobdo')

del emp_1.fullname

print(emp_1.first) # None
print(emp_1.email) # None.None@company.com
print(emp_1.fullname) # None None