1 Chapter
1 Chapter
Alex Yarosh
Content Quality Analyst @ DataCamp
Procedural programming
Great for data analysis and scripts Great for building frameworks and tools
Encapsulation - bundling data with code operating on it
numpy.ndarray
import numpy as np
a = np.array([1,2,3,4])
dir(a) # <--- list all attributes and methods
['T',
'__abs__',
...
'trace',
'transpose',
'var',
'view']
Alex Yarosh
Content Quality Analyst @ DataCamp
A basic class
class <name>: starts a class de nition
class Customer:
# code for class goes here code inside class is indented
pass
use pass to create an "empty" class
I am Customer Laura
cust = Customer()
cust.identify("Laura")
What is self?
classes are templates, how to refer data of a particular object?
Python will take care of self when method called from an object:
Attributes are created by assignment (=) in methods
Lara de Silva
Alex Yarosh
Content Quality Analyst @ DataCamp
Methods and attributes
Methods are function de nitions within a class MyClass:
class # function definition in class
# first argument is self
self as the rst argument
def my_method1(self, other_args...):
De ne a ributes by assignment # do things here
class Customer:
def __init__(self, name):
self.name = name # <--- Create the .name attribute and set it to name parameter
print("The __init__ method was called")
2. Naming
CamelCase for classes, lower_snake_case for functions and a ributes
2. Naming
CamelCase for class, lower_snake_case for functions and a ributes
class MyClass:
# This works but isn't recommended
def my_method(kitty, attr):
kitty.attr = attr
2. Naming
CamelCase for class, lower_snake_case for functions and a ributes
3. self is self
4. Use docstrings
class MyClass:
"""This class does nothing"""
pass