Difference between revisions of "Classes in Python"
Line 24: | Line 24: | ||
@property | @property | ||
def email(self): | def email(self): | ||
− | return '{}.{}@domain.com'.format( | + | email_fn = self.first_name.lower() |
+ | email_ln = self.last_name.lower() | ||
+ | return '{}.{}@domain.com'.format(email_fn, email_ln) | ||
@property | @property | ||
Line 73: | Line 75: | ||
10000 | 10000 | ||
>>> a.email | >>> a.email | ||
− | ' | + | 'adam.smith@domain.com' |
>>> a.full_name | >>> a.full_name | ||
'Adam Smith' | 'Adam Smith' |
Latest revision as of 14:17, 16 December 2018
Example
Employee Example:
Create the files:
$ mkdir models $ touch models/__init__.py $ touch models/employees.py $ vim models/employees.py
The code for the employees file:
class Employee: def __init__(self, first_name, last_name, pay): self.first_name = first_name self.last_name = last_name self.pay = pay @property def email(self): email_fn = self.first_name.lower() email_ln = self.last_name.lower() return '{}.{}@domain.com'.format(email_fn, email_ln) @property def full_name(self): return '{} {}'.format(self.first_name, self.last_name) def __repr__(self): return "Employee('{}', '{}', {})".format(self.first_name, self.last_name, self.pay)
Creating a Employee:
>>> from models.employees import Employee >>> a = Employee('Adam', 'Smith', 10000)
Help on Employee Class:
>>> help(Employee) Help on class Employee in module models.employees: class Employee | Methods defined here: | | __init__(self, first_name, last_name, pay) | | __repr__(self) | | ---------------------------------------------------------------------- | Data descriptors defined here: | | email | | full_name
Access methods and descriptors:
>>> a.first_name 'Adam' >>> a.last_name 'Smith' >>> a.pay 10000 >>> a.email 'adam.smith@domain.com' >>> a.full_name 'Adam Smith'
Resources
- Python OOP Tutorial 1: Classes and Instances
- Python OOP Tutorial 2: Class Variables
- Python OOP Tutorial 3: Class Methods and Static Methods
- Python OOP Tutorial 4: Inheritance - Creating Subclasses
- Python OOP Tutorial 5: Special (Magic/Dunder) Methods
- Python OOP Tutorial 6: Property Decorators - Getters, Setters, and Deleters
- Python SQLite Tutorial: Complete Overview - Creating a Database, Table, and Running Queries