You will be an engineer in 100 days --Day 33 --Python --Basics of the Python language 8

Today is a continuation of the basics of Python, but today the basics are over.

Click here for the last time [You will be an engineer in 100 days --Day 32 --Python --Basics of Python language 7] (https://qiita.com/otupy/items/9e70a3b36f32fccacadf)

Object-oriented story

I'm sorry if it doesn't appear

The python language is a object-oriented programming language. So what is object-oriented?

In the python language, everything handled is the concept of object. All data stored in variables is also treated as object.

** String object **

For example, if you assign the string ʻabc to the variable ʻa, This variable ʻa becomes a string type object`.

#String type object
a = 'abc'
print(a)

abc

** Functions and methods **

Next, let's declare the variable l and the element of list type.

Then this variable l becomes a list type object, At the same time, you can use the function method of the list object.

#Define list type
lis1 = [1,2,3]
#List type method
lis1.append(4)
print(lis1)

[1, 2, 3, 4]

Strictly speaking, function and method are different. To put it simply, add data as a list type ʻappend Etc. are operations on thelist objectitself It will be treated as amethod`.

In object-oriented, it is defined by an object A function that is written in the same way as a function is called a method. Others are called functions.

If you create a string type object, The function that the object has can be said to be a method.

** Concept of object thinking **

Object-oriented is a programming language composed of some kind of thing object. Objects include variables, data types, functions, and classs.

The idea of making something on the program and handling it It becomes the basic idea of object-oriented.

Because this area is conceptual You don't have to know right now, or if it's a simple program you don't know It's something that can be done. Please remember eventually.

In this next installment, I'll go into more detail about class.

About class

I'm sorry if it doesn't appear

Last time I explained the concept of object-oriented.

After learning the concept of object-oriented, the next step is actually in python Let's create a class that will be the object.

** How to make a class **

class class name():
    def __init__(self,):
processing

** How to call a class **

Variable name = class name ()

Let's create a simple class.

class class_a():
    def __init__(self,):
        print('Initialization')
        self.ac = 'aaa'

You have now created a class.

** Instance and instantiation **

A instance is amaterializedof a class.

To use data and methods of class You need to create something called an instance.

Call the class and store it in a variable. Instantiate this thing The created variable is also called instance.

#Instantiation
a = class_a()

Initialization

Here, the part of the method called ʻinitis When creating ainstance called a constructor` This is the process called at the very beginning.

When calling class and storing it in a variable ʻInit` is called and the processing in it is executed.

In this ʻinit process, there is a variable name selfas an argument. The variableself points to itself, and this argument is mandatory for class` If you do not write it, an error will occur.

In the process of ʻinit, the variable self.ac is used as a value. Substituting ʻaaa.

Now you have allocated a variable called ʻac in this class` and assigned the value. You will be able to use this variable in the part you call after creating the class.

** How to call class variables and methods **

Class variable name. Method name

aa = class_a()
print(aa.ac)

Initialization aaa

Let's add a variable for the class.

aa.b = 2
print(aa.b)

2

The variable b was allocated in the class and the value 2 was assigned. You will be able to reuse this variable later.

The variables defined in this class are called attributes.

In class, functions can be defined separately from constructor, The function defined in this class is called the method.

Let's add a method.

#Class definition
class class_a():
    def __init__(self,):
        print('Initialization')
        self.ac = 'aaa'
    #Method definition
    def anaa(self, ):
        print(1)
#Call a class and store it in a variable
aa = class_a()
#Call a method of the class.
aa.anaa()

Initialization 1

In this way, a class has multiple methods and variables. It will be a object.

The method and attribute are Because it can only be called from within that class The variable ʻac defined in class` cannot be used as it is.

print(ac)

NameError Traceback (most recent call last) in () ----> 1 print(ac) NameError: name 'ac' is not defined

Must be used with class variables.

print(aa.ac)

aaa

When do you use class? It can be used to group large processes in a program This is useful when you want to reuse it in another program.

Once as one program, classify It is common to reuse it in another program.

** Class inheritance **

The class also has the concept of inheritance.

First of all, as what is supposed to be inherited Create a parent-child class and create a method in it.

class oya():
    def oyano_method(self):
        print('oyano')

#Specify the inherited class as an argument
class ko(oya):
    def kono_method(self):
        print('kono')

For the child class, specify the parent class` as an argument.

By doing so, when you generate a child class, You will be able to use the method of the parent class.

#Call a child class.
k = ko()

#You can call the parent class inherited by the child class
k.kono_method()
k.oyano_method()

kono oyano

As you can see, it wasn't in the child class You will be able to call the method of the parent class.

This is a derivation of the existing class, When you want to create a new class, etc. This is a convenient function that can be used.

It's hard to remember the concept and mechanism of class, If you remember it, the range of programming will be greatly expanded. Please try to remember slowly and surely

Exception handling

I'm sorry if it doesn't appear

I think that error was displayed several times in the lectures so far.

For example

#Define list type
aqq = [1,2,3]
#Extract value by index
print(aqq[31])

IndexError Traceback (most recent call last) in () 2 aqq = [1,2,3] 3 # Extract value by index ----> 4 print(aqq[31]) IndexError: list index out of range

If you specify a value outside the index range of the list type list index out of range I get the error, which is an error output that is out of the list.

When such a error occurs, the program will end there. So try not to generate an error You need to take action when an error occurs.

Since it is difficult to suppress the occurrence of error, By writing a description that avoids error, the program will not be terminated.

That is exception handling.

** How to write python exception handling **

try:
processing
except:
Exception processing

Exception handling in python is where error is likely to occur Enclose it in the phrase try --except.

ʻException` is an English word meaning exception. Please remember.

try:
    aqq = [1,2,3]
    #I get an error here
    print(aqq[31])
except:
    #This is called when an error occurs
    print('error')

error

Write the processing when a error occurs in the ʻexcept` block.

If nothing is done even if a error occurs If you do not write anything, a syntax error will occur. Write pass.

try:
    aqq = [1,2,3]
    print(aqq[31])
except:
    #If you do not write any processing, an error will occur

File "", line 5

If you do not write any processing, an error will occur

^ SyntaxError: unexpected EOF while parsing

try:
    aqq = [1,2,3]
    print(aqq[31])
except:
    #If the process is undecided, write pass
    pass

In the above, you can see that the error has occurred, I don't know what's going on.

So if you can expect a error in advance You can write multiple processes when a error occurs.


try:
processing
except error name:
Exception processing
except error name:
Exception processing
try:
    aqq = [1,2,3]
    #Index error occurs here
    print(aqq[31])
except IndexError:
    #Catch the Index error here
    print('index error')
except Exception:
    print('exception')

index error

By writing error name after ʻexcept`, You can write the processing when the corresponding error occurs.

In the above example, if ʻIndex error occurs The processing of the part of ʻIndexError will be executed. ʻException` picks up all errors.

** Python error type **

ZeroDivisionError

Occurs when a number is divided by 0

1/0

ZeroDivisionError Traceback (most recent call last) in () ----> 1 1/0 ZeroDivisionError: division by zero

NameError

Occurs when trying to reference a variable or method that does not exist

print(asokokoks)

NameError Traceback (most recent call last) in () ----> 1 print(asokokoks) NameError: name 'asokokoks' is not defined

This is a grammatical mistake in the first place, so This is a usage that is not often used in try-except.

KeyError

Occurs when there is no dictionary type key

d ={1:2,3:4}
print(d[5])

KeyError Traceback (most recent call last) in () 1 d ={1:2,3:4} ----> 2 print(d[5]) KeyError: 5

There are many other errors. The following code displays a python built-in error.

[i for i in dir(__builtins__) if 'Error' in i]

['ArithmeticError',
'AssertionError',
'AttributeError',
'BlockingIOError',
'BrokenPipeError',
'BufferError',
'ChildProcessError',
'ConnectionAbortedError',
'ConnectionError',
'ConnectionRefusedError',
'ConnectionResetError',
'EOFError',
'EnvironmentError',
'FileExistsError',
'FileNotFoundError',
'FloatingPointError',
'IOError',
'ImportError',
'IndentationError',
'IndexError',
'InterruptedError',
'IsADirectoryError',
'KeyError',
'LookupError',
'MemoryError',
'NameError',
'NotADirectoryError',
'NotImplementedError',
'OSError',
'OverflowError',
'PermissionError',
'ProcessLookupError',
'RecursionError',
'ReferenceError',
'RuntimeError',
'SyntaxError',
'SystemError',
'TabError',
'TimeoutError',
'TypeError',
'UnboundLocalError',
'UnicodeDecodeError',
'UnicodeEncodeError',
'UnicodeError',
'UnicodeTranslateError',
'ValueError',
'ZeroDivisionError']

If you don't know the error that occurs, enclose it in try --except for the time being. Later, it is better to add processing according to the error content.

Be sure to remember exception handling as it is a required technique in your program.

Use of the library

I'm sorry if it doesn't appear

For the program language, you can use programs created by other people, It has convenient functions that allow you to use the programs you have created.

That is the library.

In python, there is a library that can be used immediately for work or research. There are many, such as machine learning and statistical analysis. It's easy to do with the library.

Using the library is very simple.

** How to load the library **

ʻImport library name from package name import library name`

Now let's use the library. Load the random library that produces random values.

import random

How to call the function randint () to generate a random integer random.randint (minimum, maximum)

random.randint(1,10)

10

#Call a random method 10 times
for i in range(10):
    print(random.randint(1,10))

9 5 3 8 2 9 2 1 4 7

Many libraries function specific processes. The library is also called the module in another name.

If there is an expression such as loading module, It's okay to think that you are loading a other program.

** Main python libraries **

*** os library *** You can operate files and directories on your PC

import os

#List files and folders in your PC's directory
print(os.listdir('/'))

['.DocumentRevisions-V100', '.file', '.fseventsd', '.PKInstallSandboxManager', '.Spotlight-V100', '.Trashes', '.vol', 'anaconda', 'Applications', 'bin', 'cores', 'dev', 'etc', 'home', 'installer.failurerequests', 'Library', 'Live2D_Cache', 'net', 'Network', 'opt', 'private', 'sbin', 'System', 'tmp', 'Users', 'usr', 'var', 'Volumes']

ʻOs.listdir (files, directories, etc.) `

If you specify a directory in the argument of listdir, it will be in that directory. Files and folders are returned as list values.

Find files and directories on your PC, Use the list of files to load a specific file or It is useful for writing programs that operate.

*** time library *** A library for time-related operations in a program

import time
#Stop the program for 2 seconds
time.sleep(2)
print(2)
time.sleep(1)
print(1)

2 1

** How to use your own library **

If you create a python file, you can load your own library. The extension of the library that can be imported is .py. First, let's create a simple python executable file.

This notebook is placed Create a python file in the folder. Create it with a text editor and save the extension as .py.

sample.py


def hello(aa):
    print(aa)

After creating the python file It can be read as a library, and methods etc. can be used.

#Loading your own library
import sample

#Method call
sample.hello('hello')

hello

There are innumerable libraries, and when installed with anaconda, there are about 400 types. The library is ready to use. The name of the library is confusing, so let's take a look at the installed library.

On a notebook for mac

! pip list Now you can run the command and view it.

In case of windows, at the command prompt etc. Please take ! And execute it.


! pip list
DEPRECATION: The default format will switch to columns in the future. You can use --format=(legacy|columns) (or define a format=(legacy|columns) in your pip.conf under the [list] section) to disable this warning.
adal (0.4.5)
alabaster (0.7.10)
alembic (0.9.6)
anaconda-client (1.6.3)
anaconda-navigator (1.6.2)
anaconda-project (0.6.0)
appnope (0.1.0)
appscript (1.0.1)
argcomplete (1.0.0)
asn1crypto (0.22.0)
astroid (1.4.9)
astropy (1.3.2)
azure (2.0.0rc6)
azure-batch (1.0.0)
azure-common (1.1.6)
azure-datalake-store (0.0.12)
azure-graphrbac (0.30.0)
azure-keyvault (0.3.5)
azure-mgmt (0.30.0rc6)
azure-mgmt-authorization (0.30.0)
azure-mgmt-batch (1.0.0)
azure-mgmt-cdn (0.30.3)
azure-mgmt-cognitiveservices (1.0.0)
azure-mgmt-compute (0.30.0rc6)
azure-mgmt-containerregistry (0.2.1)
azure-mgmt-datalake-analytics (0.1.6)
azure-mgmt-datalake-nspkg (2.0.0)
azure-mgmt-datalake-store (0.1.6)
azure-mgmt-devtestlabs (2.0.0)
azure-mgmt-dns (1.0.1)
azure-mgmt-documentdb (0.1.3)
azure-mgmt-iothub (0.2.2)
azure-mgmt-keyvault (0.30.0rc6)
azure-mgmt-logic (1.0.0)
azure-mgmt-monitor (0.2.1)
azure-mgmt-network (0.30.0rc6)
azure-mgmt-nspkg (2.0.0)
azure-mgmt-rdbms (0.1.0)
azure-mgmt-redis (1.0.0)
azure-mgmt-resource (0.30.0rc6)
azure-mgmt-scheduler (1.0.0)
azure-mgmt-sql (0.5.3)
azure-mgmt-storage (0.30.0rc6)
azure-mgmt-trafficmanager (0.30.0)
azure-mgmt-web (0.32.0)
azure-nspkg (2.0.0)
azure-servicebus (0.20.3)
azure-servicefabric (5.6.130)
azure-servicemanagement-legacy (0.20.4)
azure-storage (0.20.3)
Babel (2.4.0)
backports.shutil-get-terminal-size (1.0.0)
bcolz (0.12.1)
beautifulsoup4 (4.6.0)
bitarray (0.8.1)
blaze (0.10.1)
bleach (1.5.0)
bokeh (0.12.5)
boto (2.46.1)
Bottleneck (1.2.1)
bs4 (0.0.1)
certifi (2017.4.17)
cffi (1.10.0)
chardet (3.0.4)
charts (0.4.6)
chest (0.2.3)
click (6.7)
cloudpickle (0.2.2)
clyent (1.2.2)
colorama (0.3.9)
conda (4.5.11)
conda-build (3.0.19)
conda-verify (2.0.0)
configobj (5.0.6)
contextlib2 (0.5.5)
coverage (4.4.2)
cryptography (1.9)
cssselect (1.0.1)
cycler (0.10.0)
cyordereddict (1.0.0)
Cython (0.27.2)
cytoolz (0.8.2)
dask (0.14.3)
datashape (0.5.4)
decorator (4.0.11)
dill (0.2.6)
distributed (1.16.3)
Django (1.10.6)
django-bootstrap3 (8.2.2)
django-crispy-forms (1.6.1)
django-debug-toolbar (1.8)
django-pure-pagination (0.3.0)
django-registration-redux (1.5)
django-storages (1.6.3)
django-torina-blog (0.5)
docutils (0.13.1)
dynd (0.7.3.dev1)
empyrical (0.3.2)
entrypoints (0.2.2)
et-xmlfile (1.0.1)
fastcache (1.0.2)
fbprophet (0.2.1)
filelock (2.0.7)
Flask (0.12.2)
Flask-Cors (3.0.2)
future (0.16.0)
gevent (1.2.1)
glob2 (0.5)
greenlet (0.4.12)
h5py (2.7.0)
HeapDict (1.0.0)
html5lib (0.999999999)
idna (2.5)
imagesize (0.7.1)
intervaltree (2.1.0)
ipykernel (4.6.1)
ipython (5.3.0)
ipython-genutils (0.2.0)
ipywidgets (6.0.0)
isodate (0.5.4)
isort (4.2.5)
itsdangerous (0.24)
Janome (0.3.5)
jdcal (1.3)
jedi (0.10.2)
Jinja2 (2.9.6)
jsonschema (2.6.0)
jupyter (1.0.0)
jupyter-client (5.0.1)
jupyter-console (5.1.0)
jupyter-core (4.3.0)
keyring (10.4.0)
lazy-object-proxy (1.2.2)
line-bot-sdk (1.0.2)
llvmlite (0.18.0)
locket (0.2.0)
Logbook (1.1.0)
lru-dict (1.1.6)
lxml (3.7.3)
Mako (1.0.7)
MarkupSafe (0.23)
matplotlib (2.0.2)
mistune (0.7.4)
mpmath (0.19)
msgpack-python (0.4.8)
msrest (0.4.11)
msrestazure (0.4.11)
multipledispatch (0.4.9)
navigator-updater (0.1.0)
nb-anacondacloud (1.4.0)
nb-conda (2.2.0)
nb-conda-kernels (2.1.0)
nbconvert (5.1.1)
nbformat (4.4.0)
nbpresent (3.0.2)
networkx (1.11)
nltk (3.2.4)
nose (1.3.7)
notebook (5.0.0)
numba (0.33.0)
numexpr (2.6.4)
numpy (1.12.1)
numpydoc (0.6.0)
oauthlib (2.0.2)
odo (0.5.0)
olefile (0.44)
opencv-python (3.4.5.20)
openpyxl (2.4.7)
packaging (16.8)
pandas (0.20.1)
pandas-datareader (0.5.0)
pandas-highcharts (0.5.2)
pandocfilters (1.4.1)
partd (0.3.8)
pathlib2 (2.2.1)
patsy (0.4.1)
pep8 (1.7.0)
pexpect (4.2.1)
pickleshare (0.7.4)
Pillow (4.1.1)
pip (9.0.1)
pkginfo (1.4.1)
plotly (2.3.0)
ply (3.10)
prompt-toolkit (1.0.14)
psutil (5.2.2)
psycopg2 (2.7.1)
ptyprocess (0.5.1)
py (1.4.33)
py-d3 (0.2.7)
PyAlgoTrade (0.18)
pyasn1 (0.2.3)
pycosat (0.6.3)
pycparser (2.18)
pycrypto (2.6.1)
pycurl (7.43.0)
pyflakes (1.5.0)
Pygments (2.2.0)
PyJWT (1.5.2)
pylint (1.6.4)
pyodbc (4.0.16)
pyOpenSSL (17.0.0)
pyparsing (2.1.4)
pystan (2.17.0.0)
pytest (3.0.7)
python-dateutil (2.6.0)
python-editor (1.0.3)
python-highcharts (0.4.1)
pytz (2017.2)
PyWavelets (0.5.2)
PyYAML (3.12)
pyzmq (16.0.2)
QtAwesome (0.4.4)
qtconsole (4.3.0)
QtPy (1.2.1)
redis (2.10.5)
requests (2.18.1)
requests-file (1.4.2)
requests-ftp (0.3.1)
requests-oauthlib (0.8.0)
rope-py3k (0.9.4.post1)
scikit-image (0.13.0)
scikit-learn (0.18.1)
scipy (0.19.0)
seaborn (0.7.1)
selenium (3.0.2)
setuptools (27.2.0)
simplegeneric (0.8.1)
singledispatch (3.4.0.3)
six (1.10.0)
snowballstemmer (1.2.1)
sockjs-tornado (1.0.3)
sortedcollections (0.5.3)
sortedcontainers (1.5.7)
Sphinx (1.5.6)
sphinx-rtd-theme (0.2.4)
spyder (3.1.4)
SQLAlchemy (1.1.9)
sqlparse (0.2.3)
statsmodels (0.8.0)
sympy (1.0)
tables (3.4.2)
tblib (1.3.2)
terminado (0.6)
testpath (0.3)
toolz (0.8.2)
tornado (4.5.1)
traitlets (4.3.2)
unicodecsv (0.14.1)
urllib3 (1.21.1)
wcwidth (0.1.7)
webencodings (0.5)
Werkzeug (0.12.2)
wheel (0.29.0)
widgetsnbextension (2.0.0)
wrapt (1.10.10)
xlrd (1.0.0)
XlsxWriter (0.9.6)
xlwings (0.10.4)
xlwt (1.2.0)
zict (0.1.2)
zipline (1.1.1)

The name of the library does not have to be the same as this name, so If you get stuck in a search, change the name.

If you use your name, company name, nickname, etc. I think this area will be covered.

The use of libraries has become commonplace in programs, Programs that can already be used without writing the program yourself It is wise to call it from the library.

What kind of library can be used I can't show you all, so that's all for the basics.

Summary

The Python language is an object-oriented language, so all data is objects. Let's understand how to handle data together with the concept of classes.

Exception handling and loading the library are indispensable when writing a program. It's a good idea to practice how to write so that you can use both smoothly.

I can't cover all the commonly used libraries here. Let's write the code and try it while examining it for yourself.

For the frequently used code, I made a summary as a cheat sheet.

I will post a link here, so please refer to it. https://note.com/otupy/n/n1bedb9f36e54

67 days until you become an engineer

Author information

Otsu py's HP: http://www.otupy.net/

Youtube: https://www.youtube.com/channel/UCaT7xpeq8n1G_HcJKKSOXMw

Twitter: https://twitter.com/otupython

Recommended Posts

You will be an engineer in 100 days --Day 29 --Python --Basics of the Python language 5
You will be an engineer in 100 days --Day 33 --Python --Basics of the Python language 8
You will be an engineer in 100 days --Day 26 --Python --Basics of the Python language 3
You will be an engineer in 100 days --Day 32 --Python --Basics of the Python language 7
You will be an engineer in 100 days --Day 28 --Python --Basics of the Python language 4
You will be an engineer in 100 days ――Day 24 ―― Python ―― Basics of Python language 1
You will be an engineer in 100 days ――Day 30 ―― Python ―― Basics of Python language 6
You will be an engineer in 100 days ――Day 25 ―― Python ―― Basics of Python language 2
You will be an engineer in 100 days --Day 27 --Python --Python Exercise 1
You will be an engineer in 100 days --Day 34 --Python --Python Exercise 3
You will be an engineer in 100 days --Day 31 --Python --Python Exercise 2
You will be an engineer in 100 days --Day 63 --Programming --Probability 1
You will be an engineer in 100 days --Day 65 --Programming --Probability 3
You will be an engineer in 100 days --Day 64 --Programming --Probability 2
You will be an engineer in 100 days --Day 35 --Python --What you can do with Python
You will be an engineer in 100 days --Day 86 --Database --About Hadoop
You will be an engineer in 100 days ――Day 71 ――Programming ――About scraping 2
You will be an engineer in 100 days ――Day 61 ――Programming ――About exploration
You will be an engineer in 100 days ――Day 74 ――Programming ――About scraping 5
You will be an engineer in 100 days ――Day 73 ――Programming ――About scraping 4
You will be an engineer in 100 days ――Day 75 ――Programming ――About scraping 6
You will be an engineer in 100 days --Day 68 --Programming --About TF-IDF
You will be an engineer in 100 days ――Day 70 ――Programming ――About scraping
You will be an engineer in 100 days ――Day 81 ――Programming ――About machine learning 6
You will be an engineer in 100 days ――Day 82 ――Programming ――About machine learning 7
You will be an engineer in 100 days ――Day 79 ――Programming ――About machine learning 4
You will be an engineer in 100 days ――Day 76 ――Programming ――About machine learning
You will be an engineer in 100 days ――Day 80 ――Programming ――About machine learning 5
You will be an engineer in 100 days ――Day 78 ――Programming ――About machine learning 3
You will be an engineer in 100 days ――Day 84 ――Programming ――About machine learning 9
You will be an engineer in 100 days ――Day 83 ――Programming ――About machine learning 8
You will be an engineer in 100 days ――Day 77 ――Programming ――About machine learning 2
You will be an engineer in 100 days ――Day 85 ――Programming ――About machine learning 10
You will be an engineer in 100 days ――Day 60 ――Programming ――About data structure and sorting algorithm
You become an engineer in 100 days ――Day 66 ――Programming ――About natural language processing
The basics of running NoxPlayer in Python
You become an engineer in 100 days ――Day 67 ――Programming ――About morphological analysis
How much do you know the basics of Python?
What beginners learned from the basics of variables in python
Review of the basics of Python (FizzBuzz)
About the basics list of Python basics
Learn the basics of Python ① Beginners
Will the day come when Python can have an except expression?
How to know the internal structure of an object in Python
For Python beginners. You may be confused if you don't know the general term of the programming language Collection.
Check the behavior of destructor in Python
[Fundamental Information Technology Engineer Examination] I wrote an algorithm for the maximum value of an array in Python.
If you want a singleton in python, think of the module as a singleton
The story of an error in PyOCR
[Python3] Understand the basics of Beautiful Soup
The story of making Python an exe
Comparing the basic grammar of Python and Go in an easy-to-understand manner
Python Note: When you want to know the attributes of an object
Become an AI engineer soon! Comprehensive learning of Python / AI / machine learning / deep learning / statistical analysis in a few days!
I didn't know the basics of Python
The result of installing python in Anaconda
Open an Excel file in Python and color the map of Japan
In search of the fastest FizzBuzz in Python
Get a datetime instance at any time of the day in Python
An example of the answer to the reference question of the study session. In python.
[Python3] Understand the basics of file operations