Python Tutorial - Classes and Instances - 2020
Python Tutorial - Classes and Instances - 2020
PYTHON - CLASSES AND INSTANCES (__INIT__, Ph.D. / Golden Gate Ave, San Francisco / Seoul
National Univ / Carnegie Mellon / UC Berkeley /
Thank you.
- K Hong
Python
tutorial
De ning Classes
The following statement makes a class with no attributes attached, and in fact, it's an empty
namespace object: Python Home
Introduction
class Student:
pass Running Python Programs
(os, sys, import)
The name of this class is Student, and it doesn't inherit from any other class. Class names are
Modules and IDLE (Import,
usually capitalized, but this is only a convention, not a requirement. Everything in a class is
Reload, exec)
indented, just like the code within a function, if statement, for loop, or any other block of code.
The rst line not indented is outside the class. Object Types - Numbers,
Strings, and None
In the code, the pass is the no-operation statement. This Student class doesn't de ne any
methods or attributes, but syntactically, there needs to be something in the de nition, thus Strings - Escape Sequence,
the pass statement. This is a Python reserved word that just means move along, nothing to Raw String, and Slicing
see here. It's a statement that does nothing, and it's a good placeholder when we're stubbing
Strings - Methods
out functions or classes. The pass statement in Python is like an empty set of curly braces {} in
Java or C.
Formatting Strings -
expressions and method
calls
>>> Student.name = "Jack"
>>> Student.id = 20001
Files and os.path
Then, we attached attributes to the class by assigning name to it outside of the class. In this
Traversing directories
case, the class is basically an objec with eld names attached to it.
recursively
>>> print(Student.name)
Subprocess Module
Jack
1. Constructs an object
List Comprehension
__new()__
2. Initializes the object Sets (union/intersection) and
__init()__ itertools - Jaccard coe cient
and shingling to check
However, it's very rare to actually need to implement __new()__ because Python constructs our plagiarism
objects for us. So, in most of the cases, we usually only implement the special method,
Hashing (Hash tables and
__init()__.
hashlib)
Let's create a class that stores a string and a number: Dictionary Comprehension
with zip
generator.send() method
Iterators
Exceptions
When a def appears inside a class, it is usually known as a method. It automatically receives a @static method vs class
special rst argument, self, that provides a handle back to the instance to be processed. method
Methods with two underscores at the start and end of names are special methods.
Private attributes and
The __init__() method is called immediately after an instance of the class is created. It would be private methods
tempting to call this the constructor of the class. It's really tempting, because it looks like a
bits, bytes, bitstring, and
C++ constructor, and by convention, the __init__() method is the rst method de ned for the
constBitStream
class. It appears to be acting like a constructor because it's the rst piece of code executed in a
newly created instance of the class. However, it's not like a constructor, because the object has json.dump(s) and
already been constructed by the time the __init()__ method is called, and we already have a json.load(s)
valid reference to the new instance of the class.
Python Object Serialization -
The rst parameter of __init()__ method, self, is equivalent to this of C++. Though we do not pickle and json
have to pass it since Python will do it for us, we must put self as the rst parameter of
Python Object Serialization -
nonstatic methods. But the self is always explicit in Python to make attribute access more
yaml and json
obvious.
Priority queue and heap
queue data structure
SQLite 3 - B. Selecting,
Instantiating classes updating and deleting data
We can access the instance's docstring just as with a function or a module. All instances of a
Python Network
class share the same docstring. Programming I - Basic Server
/ Client : B File Transfer
Python Network
Find Your Programming II - Chat Server
/ Client
Soulmate
Python Network
Meet Charming Singles Programming III - Echo
Server using socketserver
and Get More Memorable
network framework
Dating.com Moments
Python Network
We can use the Student class de ned above as following: Programming IV -
Asynchronous Request
Handling : ThreadingMixIn
studentA = Student("Jack") and ForkingMixIn
studentB = Student("Judy", 10005)
Python Interview Questions I
Unlike C++, the attributes of Python object are public, we can access them using the dot(.)
Python Interview Questions
operator:
II
>>>studentA.name
Python Interview Questions
'Jack' III
>>>studentB.id
10005 Python Interview Questions
IV
We can also assign a new value to the attribute:
Python Interview Questions
V
>>> studentB.id = 80001
>>> studentB.id Python Interview Questions
80001 VI
Matplotlib
Let's look at another example:
Redis with Python
What is self.id?
Celluar Automata
It's an instance variable. It is completely separate from id, which was passed into the
__init__() method as an argument. self.id is global to the instance. That means that we can Batch gradient descent
access it from other methods. Instance variables are speci c to one instance of a class. For algorithm
example, if we create two Student instances with di erent id values, they will each remember
their own values. Longest Common Substring
Algorithm
Then, let's make two instances:
Python Unit Test - TDD using
unittest.TestCase class
>>> s1 = Student()
>>> s2 = Student() Simple tool - Google page
ranking by keywords
Here, we generated instance objects. These objects are just namespaces that have access to
Google App Hello World
their classes' attributes. The two instances have links back to the class from which they were
created. If we use an instance with the name of an attribute of class object, Python retrieves Google App webapp2 and
the name from the class. WSGI
Python 2 vs Python 3
virtualenv and
Math Video Courses virtualenvwrapper
Note that we stored di erent object types in the data member in each instance. In Python, bottle 0.12.7 - Fast and
there are no declarations for instance attributes (members). They come into existence when simple WSGI-micro
they are assigned values. The attribute named data does not even exist in memory until it is framework for small web-
assigned within the setData() method. applications ...
Selenium WebDriver
go through the self argument to get the instance to be processed. We can see it from the
OpenCV3 and Matplotlib ...
output:
Downloading YouTube
example B videos using youtube-dl
Superclass is listed in parenthesis in a class header as we see the example below. embedded with Python
>>> b = MyClassB()
>>> b.setData("BigData") Sponsor Open Source development activities and
free contents for everyone.
>>> b.display()
B: data = "BigData"
Thank you.
But for the instance of MyClassA is still using the display, previously de ned in MyClassA.
- K Hong
>>> a2.display()
PyQt
>>>
example C
Operator overloading allows objects intercepts and respond to operations. It makes object
interfaces more consistent and it also allows class objects to act like built-ins
class MyClassC(MyClassB):
def __init__(self, d):
self.data = d
def __add__(self,d2):
return MyClassC(self.data + d2)
def __str__(self):
return '[MyClassC: %s]' % self.data
def mul(self, d2):
self.data *= d2
MyClassC is a MyClassB, and its instances inherits the display() method from MyClassB.
>>> c = MyClassC("123")
>>> c.display()
B: data = "123"
>>> print(c)
[MyClassC: 123]
>>> c = c + '789'
>>> c.display() OpenCV 3
B: data = "123789"
>>> print(c) image and
[MyClassC: 123789]
>>> c = MyClassC('123') video
processing
>>> c.mul(3)
>>> print c
with Python
[MyClassC: 123123123]
When MyClassC is created, an argument '123' is passed. This is passed to the d argument in
the __init__ constructor and assigned to self.data. Actually, MyClassC arranges to set the data
attribute automatically at construction time. It does not require calling setdata() from OpenCV 3 with Python
instance at later time.
Image - OpenCV BGR :
Matplotlib RGB
For +, Python passes the instance object on the left of the self argument in __add__ and the
value on the right to d2. For print(), Python passes the object being printed to self in __str__. Basic image operations -
Som whatever string this method returns is taken to be the print string for the object. By pixel access
implementing __str__, we can use print to display objects of this class, and we do not have to
call the display() method. iPython - Signal Processing
with NumPy
The __add__ makes and returns a new instance object by calling MyClassC. However, mul
Signal Processing with
changes the current instance object in-place by reassigning the self attribute.
NumPy I - FFT and DFT for
sine, square waves,
unitpulse, and random
signal
We could have used the following implementing setter and getter methods:
Hough Transform - Circles
Watershed Algorithm :
class Rectangle(object):
def __init__(self, w, h):
Marker-based Segmentation
self.width = w I
self.height = h
def getWidth(self): Watershed Algorithm :
return self.width
Marker-based Segmentation
def getHeight(self):
return self.height
II
def setWidth(self, w):
self.width = w Image noise reduction : Non-
def setHeight(self): local Means denoising
self.height = h algorithm
def area(self):
return self.getWidth() * self.getHeight()
Image object detection : Face
detection using Haar
Object attributes are where we store our information, and most of the case the following Cascade Classi ers
syntax is enough:
Image segmentation -
Foreground extraction
objName.attribute # Retrieve attribute value Grabcut algorithm based on
objName.attribute = value # Change attribute value
graph cuts
However, there are cases when more exibility is required. For example, to validate the setter Image Reconstruction -
and getter methods, we may need to change the whole code like this: Inpainting (Interpolation) -
Fast Marching Methods
Properties
Machine
The solution for the issue of exibility is to allow us to run code automatically on attribute
access, if needed. The properties allow us to route a speci c attribute access (attribute's get
and set operations) to functions or methods we provide, enabling us to insert code to be run
automatically. A property is created by assigning the result of a built-in function to a class
Learning
attribute: with scikit-
learn
attribute = property(fget, fset, fdel, doc)
scikit-learn : Machine
If we go back to the earlier code, and add property(), then the code looks like this: Learning Quick Preview
scikit-learn : Data
class Rectangle(object): Preprocessing I - Missing /
def __init__(self, w, h):
Categorical data
self.width = w
self.height = h
def area(self): scikit-learn : Data
return self.width * self.height Preprocessing II -
m_area = property(area) Partitioning a dataset /
Feature scaling / Feature
We can use the class as below: Selection / Regularization
scikit-learn : Data
>>> rect = Rectangle (33, 9) Preprocessing III -
>>> rect.width, rect.height, rect.m_area Dimensionality reduction vis
(33, 9, 297) Sequential feature selection
/ Assessing feature
The example above simply traces attribute accesses. However, properties usually do compute importance via random
the value of an attribute dynamically when fetched, as the following example illustrates: forests
really runs code to compute its value when fetched. When the code runs, the value is stored in
scikit-learn : Data
the instance as state information, but whenever we retrieve it via the managed attribute, its
Compression via
value is automatically squared. Dimensionality Reduction III
- Nonlinear mappings via
kernel principal component
>>> S1 = SquareIt(4)
(KPCA) analysis
>>> S1.value
4
>>> S1.V scikit-learn : Logistic
16 Regression, Over tting &
>>> S1.V = 5 regularization
>>> S1.V
25
>>> S2 = SquareIt(64) scikit-learn : Supervised
>>> S2.value Learning & Unsupervised
64 Learning - e.g. Unsupervised
>>> S2.V PCA dimensionality
4096
reduction with iris dataset
>>>
scikit-learn :
Again, note that the fetch computes the square of the instance's data. Unsupervised_Learning -
KMeans clustering with iris
dataset
scikit-learn : Linearly
Operator overloading: 2.6 __cmp__() Separable Data - Linear
Model & (Gaussian) radial
(Removed in 3.0) basis function kernel (RBF
kernel)
By implementing __cmp__() method, all of the comparison operators(<, ==, !=, >, etc.) will work.
scikit-learn : Decision Tree
Learning I - Entropy, Gini,
So, let's add the following to our Rectangle class: and Information Gain
>>> r1 = Rectangle(100,20)
>>> print(r1)
<__main__.Rectangle object at 0x02B40750>
MACHINE LEARNING
It displays the object's class name, and its address in memory which is basically useless except ALGORITHMS AND
as a unique identi er.
CONCEPTS
So, let's add the __str__ method: Batch gradient descent
algorithm
class Rectangle(object):
Single Layer Neural Network
def __init__(self, w, h):
self.width = w
- Perceptron model on the
self.height = h Iris dataset using Heaviside
def area(self): step activation function
return self.width * self.height
def __str__(self): Batch gradient descent
return '(Rectangle: %s, %s)' %(self.width, self.height)
versus stochastic gradient
>>> r1 = Rectangle(100,20) descent
>>> print(r1)
(Rectangle: 100, 20] Single Layer Neural Network
- Adaptive Linear Neuron
The code above extends our class to give a custom display that lists attributes when our class's using linear (identity)
activation function with
instances are displayed as a whole, instead of relying on the less useful display. Note that
batch gradient descent
we're doing string % formatting to build the display string in __str__.
method
Logistic Regression
When we use print, Python will look for an __str__ method in our class. If it nds one, it will call
it. If it does not, it will look for a __repr__ method and call it. If it cannot nd one, it will create
VC (Vapnik-Chervonenkis)
an internal representation of our object. Dimension and Shatter
Bias-variance tradeo
>>> class MyClass:
def __init__(self, d):
self.data = d
Maximum Likelihood
Estimation (MLE)
>>> x = MyClass('secret')
>>> print(x) Neural Networks with
<__main__.MyClass instance at 0x027335D0>
backpropagation for XOR
>>> x
using one hidden layer
<__main__.MyClass instance at 0x027335D0>
>>>
minHash
Not much information from print(x) and just echoing the object x. That's why we do
tf-idf weight
customize the class by using __str__.
Natural Language Processing
(NLP): Sentiment Analysis I
>>> class MyClass:
(IMDb & bag-of-words)
def __init__(self, d):
self.data = d
def __str__(self): Natural Language Processing
return '[data: %s]' %self.data (NLP): Sentiment Analysis II
(tokenization, stemming, and
>>> x = MyClass('secret')
stop words)
>>> print(x), x
[data: secret] [data: secret]
>>> myObjects = [MyClass('A'), MyClass('B')] Natural Language Processing
>>> for obj in myObjects: (NLP): Sentiment Analysis III
print(obj) (training & cross validation)
[data: A]
[data: B]
Natural Language Processing
(NLP): Sentiment Analysis IV
(out-of-core)
But not when we use print(myObjecs). Note that the instances are in the list:
Locality-Sensitive Hashing
(LSH) using Cosine Distance
>>> print(myObjects)
(Cosine Similarity)
[<__main__.MyClass instance at 0x02733800>, <__main__.MyClass instance at 0x027338C8>
>>> myObjects
[<__main__.MyClass instance at 0x027338C8>, <__main__.MyClass instance at 0x027336C0>
The rst argument, sys.argv[0], is actually the name of the program. It exists so that we can
change our program's behavior depending on how it was invoked. For example:
# t.py
if __name__ == '__main__':
import sys
print('program: %s' %sys.argv[0])
for arg in sys.argv[1:]:
print('Arg: %s' %arg)
C:\TEST>python t.py
program: t.py
C:\TEST>python t.py A B C
program: t.py
Arg: A
Arg: B
Arg: C
long_options, if speci ed, must be a list of strings with the names of the long options which
should be supported. The leading -- characters should not be included in the option name.
Long options which require an argument should be followed by an equal sign (=). Optional
arguments are not supported. To accept only long options, options should be an empty string.
Long options on the command line can be recognized so long as they provide a pre x of the
option name that matches exactly one of the accepted options:
For example, if long_options is ['foo', 'frob'], the option --fo will match as --foo, but --f will not
match uniquely, so GetoptError will be raised.
Each option-and-value pair returned has the option as its rst element, pre xed with a hyphen
for short options (e.g., '-x') or two hyphens for long options (e.g., '--long-option'), and the
option argument as its second element, or an empty string if the option has no argument. The
options occur in the list in the same order in which they were found, thus allowing multiple
occurrences. Long and short options may be mixed.
-from http://docs.python.org/2/library/getopt.html.
# option.py
def main():
in_filename = 'fin'
out_filename = 'fout'
try:
options, remainder = getopt.getopt(sys.argv[1:], 'i:o:', ['input=', 'output='
except getopt.GetoptError:
sys.exit()
return 0
if __name__ == "__main__":
sys.exit(main())
Note that the long option does not have to be fully matched:
__call__
Python runs a __call__ method when an instance is called as a function form. This is more
useful when we do some interfacing work with APIs expecting functions. On top of that, we
can also retain state info as we see in the later examples of this section.
It is believed to be the third most commonly used operator overloading method, behind the
__init__ and the __str__ and __repr__ according to Mark Lutz (Learning Python).
Here is an example with a __call__ method in a class. The __call__ method simply prints out the
arguments it takes via keyword args.
>>> A = Called()
>>> A('psy', 'Gangnam', 'Style')
I've just called: ('psy', 'Gangnam', 'Style') {}
>>> A (2013, 'Sept', 16, Singer='psy', Title='Gangnam Style')
I've just called: (2013, 'Sept', 16) {'Singer': 'psy', 'Title': 'Gangnam Style'}
While the __call__ method allows us to use class instances to emulate functions as we saw in
the above examples, there is another use of __call__ method: we can retain state info:
>>> S = State(100)
>>> S(99)
199
>>> S(77)
177
>>>
BogoToBogo [email protected]
[email protected]
Golden Gate Ave, San Francisco, CA 94115