-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclass_and_objects.py
More file actions
executable file
·87 lines (71 loc) · 2.37 KB
/
class_and_objects.py
File metadata and controls
executable file
·87 lines (71 loc) · 2.37 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Short example on object and class manipulation.
See detail here: https://www.freecodecamp.org/news/python-property-decorator/
"""
class Person():
""" Class for representing a person
Attributes
----------
eye_color : string
The color of person's eyes
nb_eyes : int
The number of eyes of the person
Methods
-------
__len__()
Returns the number of eyes of the person
__str__()
Returns a string representation of the person
"""
def __init__(self, eye_color, nb_eyes=2):
""" Constructor for the Person class
Parameters
----------
eye_color : string
The color of person's eyes
nb_eyes : int, optional
The number of eyes of the person, default to 2
"""
# This will use the setter function below
self.eye_color = eye_color
self.nb_eyes = nb_eyes
# This will NOT use the setter function below
# self._eye_color = eye_color
# self._nb_eyes = nb_eyes
def __len__(self):
""" Returns the number of eyes of a person """
return self.nb_eyes
def __str__(self):
""" Returns a string representation of a person with their eye color
and number of eyes
"""
return 'This person has {} {} eyes.'.format(self.nb_eyes,
self.eye_color)
@property
def eye_color(self):
""" Returns the eye color of a person """
return self._eye_color
@eye_color.setter
def eye_color(self, eye_color):
""" Set the eye color of a person """
if not isinstance(eye_color, str):
raise ValueError('Invalid value for eye_color (not string)!')
self._eye_color = eye_color
@property
def nb_eyes(self):
""" Returns the number of eyes of a person """
return self._nb_eyes
@nb_eyes.setter
def nb_eyes(self, nb_eyes):
""" Set the number of eyes of a person """
if not isinstance(nb_eyes, int):
raise ValueError('Invalid value for nb_eyes (not integer)!')
self._nb_eyes = nb_eyes
person_1 = Person('green', 2)
person_2 = Person('blue', 1)
print(person_1)
print(len(person_1), person_1.eye_color, person_1.nb_eyes)
# person_3 = Person(['black'], 2)
# person_3 = Person('black', 2.0)