Python memo

Python image post

https://nktmemo.wordpress.com/2014/01/05/画像のurlを受け取りbase64テキストに変換する(python)/

Use class to create a new data type

[Example: Dice type with only name, which has no function]

>>> class Dice:
...     pass
...

[Call instance]

>>> sai = Dice()

If no error occurs, a new Dice type has been prepared and assigned to the variable sai.

What is a "new data type"?

The nature is determined by the attribute (attribute), Create functions by methods.

Example) Dice ・ Properties: 6 sides and numbers engraved on them ・ You can roll and decide one number

[Data type] -A collection of simpler data attributes (attributes) and functions (methods). "Attribute" and "Method" How it is The mechanism (blueprint) that determines is the concept of class.

Class is a blueprint of data type
Create new data type with class keyword

Add a data attribute to the Dice type that represents the number of dice faces.

>>> class Dice:
...     face_num = 6
...
>>> 

Call an instance

>>> sai = Dice()
>>> sai.face_num

6

A new data attribute, face_num, has been added to the Dice type. You can see that 6 is stored.

Think about the difference between methods and functions

[A function that randomly returns a number from 1 to 6]

>>> import random
>>>
>>> def shoot():
...     return random.randint(1,6)
...

If you put this function in the class as it is, it will not function as a method.

Then what should we do

Rules that define methods

--Method requires "self" as first argument

-"Self" that must write one argument

sample.py


Put together as a module

>>> import random
>>>
>>> class Dice:
...     face_num = 6
...     def shoot(self):
...             return random.randint(1,6)
... 

>>> sai = Dice()
>>> sai.shoot()
5

face_num = 6 is not used For example

※error

err.py


>>> import random
>>>
>>> class Dice:
...     face_num = 6
...     def shoot(self):
...             return random.randint(1,face_num)
... 

This will result in an error. face_num = 6 You cannot see outside variables from inside the method. It is decided that the data used inside the function is passed as an argument

face_num is a data attribute that the Dice type has by itself, so It is troublesome to bother to pass it as an argument to the method. As the number of data attributes increases, the number of method arguments increases, which becomes difficult.

When preparing an instance, I don't know what variable name the user will assign. It is decided to call the instance "self" in the first argument of the method so that an instance of Dice type can be created with any name.

Decide to refer to yourself

sample.py


>>> class Dice:
...     face_num = 6
...     def shoot(self):
...             return random.randint(1,self.face_num)
...
When I created the function, I could see the variables outside the function, but why is the face right next to it here?_Can't you see num?

The range from which a variable can be referenced is determined by the defined location.
scope.

Scope type

-Built-in scope (scope to which the built-in function belongs can be freely referenced from anywhere) -Module scope (when a new module is created) -Local scope (when creating a function or method)

What you can see from where you are Only "built-in scope" and "module scope" to which you belong.

import random

random.randint(1,10)

If you give it the name random like this, you can refer to it. It is called "namespace".

sample.py



#! /usr/bin/python
#-*- coding:utf-8 -*-

import dice

sai = dice.Dice()
count = sai.shoot()
print(count)

sample.py



import random

class Dice:
        face_num = 6
        def shoot(self):
            return random.randint(1,self.face_num)

The identity of the initialization method

When preparing an instance with a data type other than the built-in data type, it was necessary to call the initialization method. Since the created Dice type is not a built-in data type, I wrote it as follows.

sai = dice. Dice()

I always do it like this. This calls an initialization method with no arguments. When you create a "new data type" using class, Python automatically provides an initialization method with no arguments. What if I want to change the behavior of this initialization method?

The real name of the initialization method init

[Complete]

dice.py


import random

class Dice:
        face_num = 6
        def __init__(self):
            print("Hello")

        def shoot(self):
             return random.randint(1,self.face_num)

sample.py



#! /usr/bin/python
#-*- coding:utf-8 -*-

import dice

sai = dice.Dice()
count = sai.shoot()
print(count)

Hello
2

Modify the Dice type

When you call the initialization method so that you can realize various types of dice with Dice type Arguments 4, 6, 8, 12, 20 Specify one of the integers of Be able to determine the shape of the dice.

dice2.py



import random

class Dice:
    def __init__(self,val):
        self.face_num = val

    def shoot(self):
         return random.randint(1,self.face_num)

test10.py



import dice2

sai = dice2.Dice(4)
count = sai.shoot()
print(count)

If no arguments are given, an error will occur

Set the default value of the argument val in dice2.py

import random

class Dice:
    def __init__(self,val=6):
        self.face_num = val

    def shoot(self):
         return random.randint(1,self.face_num)

development

There are only 5 types of regular tetrahedron, but the current Dice type is an argument of the initialization method. Any value will be specified. Therefore, Check the argument with the initialization method and give an error if it is not possible.

Whether or not the argument is a specified number is determined using the keyword in and a list.

>>> 4 in [4,6,8,12,20]
True

>>> 7 in [4,6,8,12,20]
False

>>> 7 not in [4,6,8,12,20]
True

dice3.py


#coding:UTF-8

import random

class Dice:
    def __init__(self,val=6):
        if val not in [4,6,8,12,20]:
            raise Exception("There is no such polyhedron.")
            self.face_num = val

    def shoot(self):
        return random.randint(1,self.face_num)

test10.py



import dice3

sai = dice3.Dice(99)
count = sai.shoot()
print(count)

dice3.py



#! /usr/bin/python
#-*- coding:utf-8 -*-

import random

class Dice:
    def __init__(self,val=6):
        if val not in [4,6,8,12,20]:
            #raise Exception("There is no such polyhedron")
            print("There is no such polyhedron")
        self.face_num = val

    def shoot(self):
        return random.randint(1,self.face_num)
-*- coding:utf-8 -*-

import dice3

num = input("4,6,8,12,Which of the 20 will you play?:")
my_dice = dice3.Dice(num)
cpu_dice = dice3.Dice(num)

my_pip = my_dice.shoot()
cpu_pip = cpu_dice.shoot()

Convert numbers to strings using the str function

print("CPU:"+ str(cpu_pip) + "you"+ str(my_pip))

if my_pip > cpu_pip:
    print("Congratulations. You win")
elif my_pip < cpu_pip:
    print("Sorry!You lose")
else:
    print("It's a draw")

Summary

· Data types are made up of data attributes and methods ・ To create a new data type, create a class that will be a blueprint. ・ Classes organize data attributes (attributes) and methods -Methods are added to the class using the def keyword, just like functions -The method must always have "self" as the first argument -The substance of the initialization method is a method named init

What is Django

A web application framework implemented in Python. A framework that inherits the MVC (Model-view-Controll) architecture.

Django reduces the amount of code and makes it easy to build complex database-centric websites.

https://django-docs-ja.readthedocs.org/

Installation

pip install django

project

A project is a Python package with all the settings for a Django instance. ・ Create one website as one project. -Create and place a new project-specific application in the project -Has settings for each website (database settings, Django option settings, application settings, etc.).

django-admin command

By executing "start project", the project directory (myprj) and Initial file is created

django-admin startproject myprj

・ Myprj/
・ Manage.py
・ Myprj
・__init__.py
・ Settings.py
・ Urls.py
・ Wsgi.py

application

The contents are just a Python package. It doesn't matter where you put it wherever PYTHON goes.

When creating polls directory and initial files

cd myprj
python manage.py startapp polls

model

Django offers an O / R mapper. You can write a database layout in Python code.

Each model is a Python class that inherits from the django.db.models.Model class and corresponds to one table in the database.

URL dispatcher

・ URL pattern written in regular expression -Write in the "URLconf" module that defines the mapping of Python functions. (Can be divided for each application) (By defining the URL with a name, you can refer to the URL by that name from the code or template.)

View

Function that returns an HTTP response -HttpResponse object of the requested page · Exceptions like Http404

A typical view function is

  1. Get data from request parameters
  2. Load the template
  3. Render and return the template using the acquired data

http://django-docs-ja.readthedocs.org/en/latest/contents.html

Recommended Posts

Python memo
python memo
Python memo
python memo
Python memo
Python memo
Python memo
[Python] Memo dictionary
python beginner memo (9.2-10)
python beginner memo (9.1)
★ Memo ★ Python Iroha
[Python] EDA memo
Python 3 operator memo
[My memo] python
Python3 metaclass memo
[Python] Basemap memo
Python beginner memo (2)
[Python] Numpy memo
Python class (Python learning memo ⑦)
python openCV installation (memo)
Python module (Python learning memo ④)
Visualization memo by Python
Python
Python test package memo
[Python] Memo about functions
python regular expression memo
Binary search (python2.7) memo
[My memo] python -v / python -V
Python3 List / dictionary memo
[Memo] Python3 list sort
Python Tips (my memo)
[Python] Memo about errors
DynamoDB Script Memo (Python)
Python basic memo --Part 2
python recipe book Memo
Basic Python command memo
Python OpenCV tutorial memo
Python basic grammar memo
TensorFlow API memo (Python)
python useful memo links
Python decorator operation memo
Python basic memo --Part 1
Effective Python Memo Item 3
Divisor enumeration Python memo
Python memo (for myself): Array
Python exception handling (Python learning memo ⑥)
Python execution time measurement memo
Twitter graphing memo with Python
[Line / Python] Beacon implementation memo
Python and ruby slice memo
Python Basic Grammar Memo (Part 1)
Python code memo for yourself
Raspberry Pi + Python + OpenGL memo
Python basic grammar (miscellaneous) Memo (3)
Python immutable type int memo
Python memo using perl --join
Python data type summary memo
Python basic grammar (miscellaneous) Memo (2)
[MEMO] [Development environment construction] Python
[Python] virtualenv creation procedure memo
Python basic grammar (miscellaneous) Memo (4)