Classes in Python

From Knowledge Center
Revision as of 15:11, 16 December 2018 by Ruan (talk | contribs)
Jump to: navigation, search

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):
        return '{}.{}@domain.com'.format(self.first_name, self.last_name)

    @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