Python Basics

Declare Your First Python Class — Understand 3 Basic Components

Better organize your code using custom classes

Yong Cui
Yong Cui
May 24, 2020 · 7 min read
Image for post
Image for post
Photo by SpaceX on Unsplash
>>> employee = {"name": "John Smith", "employee_id": 10997, "gender": "M"}
>>> employee["name"]
'John Smith'
>>> employee["gender"]
'M'
>>> employee["employe_id"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'employe_id'

1. Instantiation

>>> # Define a class
>>> class Employee:
... def __init__(self):
... print("An employee instance is created")
...
>>> # Create an instance
>>> employee = Employee()
An employee instance is created
>>> # Check the variable employee's type
>>> type(employee)
<class '__main__.Employee'>
>>> isinstance(employee, Employee)
True

2. Attributes

>>> # Update the class's init method
>>> class Employee:
... def __init__(self, name, employee_id, gender):
... self.name = name
... self.employee_id = employee_id
... self.gender = gender
...
>>> # Create an instance
>>> employee = Employee("John Smith", 10997, "M")
>>> # Access the instance's attributes
>>> employee.employee_id
10997
>>> employee.gender
'M'
>>> employee.name = "John David Smith"
>>> employee.name
'John David Smith'
>>> # Create another instance
>>> another_employee = Employee("Jennifer Davis", 11308, "F")
>>> another_employee.name
'Jennifer Davis'
>>> another_employee.employee_id
11308
>>> another_employee.gender
'F'
>>> # Update the class with a class attribute
>>> class Employee:
... company = "Python Foundation"
... # same __init__ function as before
...
>>> # Create new instances
>>> employee0 = Employee("Aaron", 20313, "M")
>>> employee1 = Employee("Jimmy", 20443, "M")
>>>
>>> # Access class attributes
>>> employee0.company
'Python Foundation'
>>> employee1.company
'Python Foundation'
>>> Employee.company
'Python Foundation'
>>> # Update the class attribute
>>> Employee.company = "Python"
>>> Employee.company
'Python'
>>> employee0.company
'Python'

3. Methods

>>> # Update the class with some methods
>>> class Employee:
... # Keep the init method the same
...
... # Declare an instance method
... def request_vacation(self, start_date, days):
... print(f"Request {days} days off starting on {start_date}")
...
... # Declare a static method
... @staticmethod
... def send_notice(content):
... print(f"Every employee is notified: {content}")
...
>>> # Create an instance
>>> employee = Employee("David Johnson", 20340, "M")
>>>
>>> # Call the instance method
>>> employee.request_vacation("2020-06-02", 10)
Request 10 days off starting on 2020-06-02
>>>
>>> # Call the static method
>>> Employee.send_notice("Hello")
Every employee is notified: Hello
>>> employee.send_notice("Hello")
Every employee is notified: Hello
>>> # Call the instance method with the class
>>> Employee.request_vacation("2020-06-02", 10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: request_vacation() missing 1 required positional argument: 'days'

Conclusions

The Startup

Medium's largest active publication, followed by +755K people. Follow to join our community.

Yong Cui

Written by

Yong Cui

Work at the nexus of biomedicine, data science & mobile dev. Love to write on these technological topics. Follow me @ycui01 on Twitter to get latest articles.

The Startup

Medium's largest active publication, followed by +755K people. Follow to join our community.

Yong Cui

Written by

Yong Cui

Work at the nexus of biomedicine, data science & mobile dev. Love to write on these technological topics. Follow me @ycui01 on Twitter to get latest articles.

The Startup

Medium's largest active publication, followed by +755K people. Follow to join our community.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store