SNS Python basics made with Flask

at first

Udemy course attendance record

Web application development course with Python + Flask! !! ~ Master Flask from 0 to create SNS ~ https://www.udemy.com/course/flaskpythonweb/

The basic grammar of Python and the application creation using Flask are described separately.

--Environment is done on the container created by the docker image of Anaconda.

Virtual environment construction

Create a virtual environment for creating applications using venv.

1. Creating a virtual environment

(base) root@e8cf64ce12e9:/home/venv/flaskenv# python -m venv flaskenv

2. Start virtual environment

-The name of the started virtual environment is displayed with () at the beginning of the line.

(base) root@e8cf64ce12e9:/home/venv/flaskenv# source bin/activate
(flaskenv) (base) root@e8cf64ce12e9:/home/venv/flaskenv# 

·Stop

(flaskenv) (base) root@e8cf64ce12e9:/home/venv/flaskenv# deactivate
(base) root@e8cf64ce12e9:/home/venv/flaskenv# 

Git registration

1. Create a repository on Github

abridgement

2. Local Git registration and Github integration

kekosh@kekosh-mbp flaskenv % git init
Initialized empty Git repository in /Users/kekosh/work/docker/venv/flaskenv/.git/

kekosh@kekosh-mbp flaskenv % git add .

kekosh@kekosh-mbp flaskenv % git commit -m 'first commit'

kekosh@kekosh-mbp flaskenv % git remote add origin  [email protected]:kekosh/flask-sns.git

kekosh@kekosh-mbp flaskenv % git push -u origin master

When changing the Github repository (after "remote add ....")

kekosh@kekosh-mbp flaskenv % git remote rm origin

Mac notes

For Mac, a hidden file called ".DS_Store" is created in each directory. Since this is not a file that should be managed by Git, register it as unmanaged in gitignore before committing.

.gitignore


# Mac
.DS_Store

If you have already linked to Github, delete the Git cache after adding the above to .gitignore Make it unmanaged from the next commit.

kekosh@kekosh-mbp flaskenv % git rm -r --cached .

Python

all (collection of and conditions)

Takes a tuple that summarizes multiple comparison conditions as an argument. Returns True if all conditional expressions are True

>>> i = 0
>>> x = 'test'
>>> if all((i<10, x =='test')):
...     print('All True')
... 
All True

any (aggregate of OR conditions)

Takes a tuple that summarizes multiple comparison conditions as an argument. Returns True if any one of the conditional expressions is True.

>>> i = 0
>>> x = 'any'
>>> if any((i > 10, x == 'any' )):
...     print('Including True')
... 
Including True

enumerate (get index at the same time)

>>> list = ['taro','jiro','sabu','shiro']
>>> for i, v in enumerate(list):
...     print(i, v)
... 
0 taro
1 jiro
2 sabu
3 shiro

zip (get values from two arrays at the same time)

>>> list_a = ['cat','dog','rabbit']
>>> list_b = ['mike','jhon','usa']
>>> for a, b in zip(list_a,list_b):
...     print(a, b)
... 
cat mike
dog jhon
rabbit usa

Walrus operator (assign to variable and use at the same time. Python3.8 or later)

abridgement

import traceback (get error details)

m = 100
n = input()

try:
    result = m /int(n)
    print(result)
except ZeroDivisionError as ze:
    import traceback
    traceback.print_exc()
print('end')
#result
kekosh-mbp:flaskenv kekosh$ python main.py
0
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    result = m /int(n)
ZeroDivisionError: division by zero
end

try ~ except ~ else ~ finally

--other: Process to be executed only when no error occurs. The Exception that occurs here is not caught by the previous except. --finally: Process that is always executed regardless of the presence or absence of an error.

try:
    #Main processing
except XXXXXX as e:
    #Processing to be executed when a specific exception occurs
except Exception e:
    #Processing when all exceptions occur except exceptions that describe specific processing
else:
    #Processing that is executed only when an exception does not occur
finally:
    #Processing that is always executed regardless of the presence or absence of exceptions

raise Exception (intentionally returns a specific exception)

raise ZeroDivisionError('Not divisible by zero')

Create your own exception

Create a class that inherits the Exception class.

#template
class MyException(Exception)
    print('Proprietary error occurred')
#Implementation example
class EvenDevideError(Exception):
    pass

def main():
    m = 10
    n = int(input('input:'))

    if n == 2:
        raise EvenDevideError('even number input')
    else:
        print('end')

if __name__ == '__main__':
    main()
#result
kekosh-mbp:flaskenv kekosh$ python main.py
Input: 2
Traceback (most recent call last):
  File "main.py", line 14, in <module>
    main()
  File "main.py", line 9, in main
    raise EvenDevideError('even number input')
__main__.EvenDevideError: even number input

Variadic argument

--Variadic argument is behind the argument --def func (arg1, * arg2): The arguments passed to "* args2" are passed to the function as tuples. --def func (arg1, ** arg2): The arguments passed to "** arg2" are passed to the function as a dictionary type.

>>> def func_1(arg1, *arg2):
...     print("arg1={}, *arg2={}".format(arg1, arg2))
... 
>>> def func_2(arg1, **arg2):
...     print("arg1={}, **arg2={}".format(arg1, arg2))

#If you pass multiple values"*"Set the values one by one from the front to the variables without
#The remaining argument values are collectively set in arg2 as a tuple.
>>> func_1(1,2,3,4,5)
arg1=1, *arg2=(2, 3, 4, 5)

#"**"In the case of, when passing a value, just like a dictionary variable"id=1"In a format like
#You need to set the arguments.
>>> func_2(1,2,3,4,5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: func_2() takes 1 positional argument but 5 were given
>>> 
>>> func_2(1, id=1, name='taro')
arg1=1, **arg2={'id': 1, 'name': 'taro'}

Generator function

--yield val: Stops function processing at'yield'and returns the yield variable to the caller. --The processing below'yield'is executed by calling it as'next (func)'.

def generater(max):
    print('Generator creation')

    for i in range(max):
        #Processing stops at yield when creating an instance, and a variable of yield is returned to the caller.
        yield i
        print('yield execution')

gen = generater(10)

#next()By passing the generator function to, the processing after yield is executed.
n = next(gen)
print('n = {}'.format(n))
n = next(gen)
print('n = {}'.format(n))

#next()It is also possible to execute by loop processing instead
for x in generater(10):
    print('x = {}'.format(x))
Generator creation
n = 0
yield execution
n = 1

--In addition to the next () function, the generator function has the following methods. --send (val): If'yield'in the generator function is assigned to a variable, assign the value of val to that variable.

def gengerator(max)
    #abridgement
    for i in generator()
        x = yield i
        print(x)

gen = generator(10)
#After stopping the treatment with yield, send to the variable where yield is stored(val)Store the val of.
gen.send(100)

--generator.throw (err_value): Intentionally generate an error. --generator.close (): End of yield processing

Sub-generator

--yield from sub generator: You can call another generator function from a generator function.

def sub_gen():
    yield 'sub_generator'
    print('on sub_gen')
    return 'sub_gen'

def main_gen():
    yield 'main_generator'

    #Call the sub-generator with yield from
    res = yield from sub_gen()
    print(res)
    return 'main_gen'

gen = main_gen()
print(next(gen))
print(next(gen))
print(next(gen))
main_generator
sub_generator
on sub_gen
sub_gen
Traceback (most recent call last):
  File "d:/MyFile/arc/pyenv/py-outlook/app.py", line 17, in <module>
    print(next(gen))
StopIteration: main_gen

--When a sub-generator is called with'yield from', processing is stopped at'yield val'and the value of val is returned to the caller, as with a normal generator. --The next time it is executed (next (), etc.), the next processing will be executed from the position of'yield' where the processing was stopped. --An error is returned because the generator processing is finished at the time of the third print () above.

Generator usage

--The generator is used to reduce memory usage. --If you declare a List type variable and store tens of thousands of data, the memory usage will be enormous, but if you create a List type variable using a generator, the memory usage can be significantly reduced.

Higher-order function

--Assigning a function to a variable. --For higher-order functions, do not add "()" to the function when assigning it to a variable.

def print_hello(func):
    print('hello')
    func('taro')
    return print_message

def print_bye(name='someone'):
    print('good bye, {}'.format(name))

def print_message():
    print('The return value is a function')

#pattern1.Store function as a list element
list = [1, 'test', print_bye, print_hello]

#pattern1.When executing a higher-order function, "" after the index()"
list[2]()

#pattern2.Pattern to pass a function as a function argument (return value is also a function)
var = print_hello(print_bye)
var()
#Result of pattern1
good bye, someone

#Result of pattern2
hello
good bye, taro
The return value is a function

lambda expression

--A function defined in one line excluding the function name from the normal function (def) (anonymous function) --Anonymous function lambda argument: Return value processing

#lambda expression in if statement
def func(x):
    response = ''

    #Normal if statement
    if x > 5:
        response = 'large'
    else:
        response = 'small'

    return response

    #lambda format
    response = 'large' if x > 5 else 'small'
    return response

x = int(input('input:'))
res = func(x)
print(res)
>>> func = lambda x,y,z : x*y*z if z > 10 else x*y
>>> 
>>> func(1,2,3)
2
>>> func(1,2,15)
30

Recursion

--To execute the function itself within the function.

>>> def fib(n):
...     n = int(n)
...     return n if n <= 2 else fib(n-1) + fib(n-2)
>>> for i in range(1,10):
...     print(fib(i))
... 
1
2
3
5
8
13
21
34
55

List comprehension

--Variable name = [expression for variable in list (if expression)] --In addition to list type, if you define parentheses with parentheses, it becomes a generator, and if you add "tuple" before the parentheses, it returns a tuple format result. In the case of set type, set the parentheses to {}. --It is also possible to execute a function in a list comprehension and set the result as an element of the list.

#List comprehension notation to create a list
>>> list_a = [x * 2 for x in range(1,10)]
>>> print(list_a)
[2, 4, 6, 8, 10, 12, 14, 16, 18]
>>>
>>> list_b = [x * 2 for x in range(1,10) if x % 2 == 0]
>>> print(list_b)
[4, 8, 12, 16]
#List comprehension notation for tuple creation
>>> list_c = tuple(x for x in range(10))
>>> list_c
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> type(list_c)
<class 'tuple'>

Decorator function

--By defining the process you want to execute in common for multiple functions as a decorator function and placing it in front of the target function as'@decorator function name', the process of the decorator function when the function with the decorator function set is executed. Are executed together.

#Define decorator function
def decorator(func):
    def wrapper(*args, **kwargs):
        print('*' * 30)
        #Argument: func is set to a function object with a decorator set.
        func(*args, **kwargs)
        print('*' * 30)
    return wrapper

#The function with the decorator set in the argument of the decorator function is set and executed.
@decorator
def func_a(*args, **kwargs):
    print('func_Run a')
    print(args)

@decorator
def func_b(*args, **kwargs):
    print('func_Run b')
    print(kwargs)

func_a(1,2,3)
func_b(4,5,6,id=4,name='test')
kekosh-mbp:flaskenv kekosh$ python decorator.py
******************************
func_Run a
(1, 2, 3)
******************************
******************************
func_Run b
{'id': 4, 'name': 'test'}
******************************

map function

--map ([function], [variable passed to function] ...) --Returns the result of processing by sequentially acquiring elements from iterated type variables such as list type and dictionary type specified after the second argument in the argument of the function specified in the first argument.

#Typical example: List type as the second argument
list_a = [1,2,3,4,5]
map_a = map(lambda x: x*2, list_a)

#Check the contents of the map type object with the for statement
for x in map_a:
    print(x)

#Dictionary type arguments can also be used
person = {
    'name': 'Yamada'
    ,'age': '34'
    ,'country': 'Japan'
}

#Function part can also describe lambda expression
map_b = map(lambda d : d+ ',' + person.get(d), person)
for m in map_b:
    print(m)

'''
When passing multiple arguments to a function, between the iterator expression variables passed to the function of the first argument
If the number of elements is different, round down too much according to the one with the smallest number of elements.
'''
list_x = ['apple','grape','lemon','peach']
dic_x = {'apple':'150','grape':'140','lemon':'110','peach':'180'}
tuple_x = tuple(x for x in range(1,5))

def mapping(name,dic,count):
    fruit = name
    price = dic_x.get(fruit)
    return fruit +  ':' + str(price) + ':' + str(count)

map_c = map(mapping,list_x,dic_x,tuple_x)
for mc in map_c:
    print(mc)
2
4
6
8
10
name,Yamada
age,34
country,Japan
apple:150:1
grape:140:2
lemon:110:3
peach:180:4

Class definition

#Class definition template
class className:
    """Comments explaining the function of the class"""
    def methodName(self,...):
        #processing

#Create an instance to use the defined class
instance = className()
#<sample>
#Class definition
class Car:
    country = 'japan'
    year = 2020
    name = 'Prius'

    #When defining a method in a class, make sure that the first argument of the method is "self".
    def print_name(self):
        print('Method execution')
        print(self.name)

my_Car = Car()
print(my_Car.year)
my_Car.print_name()

#Use a class (instance) for one element of list type
list = ['apple', 'banana', Car()]
list[2].print_name()

Class variables and instance variables

** Class variables ** --Variables that can be shared between objects --List directly under the class

how to access --Class name. Class variable name --Instance name. \ _ \ _ Class__. Class variables ** * If \ _ \ _ class \ _ \ _ is not described (instance name.class name), the data that can be acquired is different from the class variable (instance variable is acquired) **

Instance variables --Variables used separately for each instance --Description in the method

how to access Instance name.variable

class SampleA():
    #Class variables
    class_val = 'class val'

    def set_val(self):
        #Instance variables
        self.instance_val = 'instance val'

    def print_val(self):
        print('Class variables:{}'.format(self.class_val))
        print('Instance variable:{}'.format(self.instance_val))

#Instance creation
instance_A = SampleA()
#Instance method call
instance_A.set_val()
print(instance_A.instance_val)
instance_A.print_val()

#Output of class variables
print(SampleA.class_val)
print(instance_A.__class__.class_val)

print('---------------------')

#Create a new instance from the class
instance_B = SampleA()
instance_B.class_val = 'change'

#If you change the value of a class variable from one instance, even if you refer to the class variable from another instance
#Note that the value will change.
print('instance_Class variable of A:{}'.format(instance_A.__class__.class_val))
print('instance_Class B variables:{}'.format(instance_B.__class__.class_val))
instance val
Class variable: class val
Instance variables= instance val
class val
class val
---------------------
instance_Class variable of A: class val
instance_Class B variable: class val
kekosh-mbp:flaskenv kekosh$ 

constructor

--Methods called when creating an instance

class Sample:
    #constructor
    def __init__(self, msg, name=None):
        print('Constructor execution')

        #Assign the value of the argument to the instance variable
        self.msg = msg
        self.name = name

    def print_msg(self):
        print(self.msg)

    def print_name(self):
        print(self.name)

inst_1 = Sample('hello', 'taro')
inst_1.print_msg()
inst_1.print_name()
#The constructor is automatically executed when the instance is created.
Constructor execution
hello
taro

Destructor

--Process that is called when the instance is deleted (at the end of use)

#Destructor
def __del__(self):
    print('Destructor ran')
    print('name = {}'.format(self.name))
#At the end of instance processing (including when deleted by del instance name)
Destructor ran
name = taro

Method type

** Instance method ** --Of the methods defined in the class, the methods that will be available after the instance is created. The first argument is always self. self refers to oneself. --It is possible to use class methods and static methods from instance methods.

** Class methods ** Methods that can be used without instantiation. Write "@classmethod" directly above the method definition, and set the first argument to "cls". --Class method can be executed with class name.class method name (). --cls means class itself --Cls. You can access class variables with the class variable name. --You cannot access instance variables with class methods.

** Static method ** --Write "@staticmethod" directly above the method definition. --Functions that neither class variables nor instance variables can access.

class Human:

    class_name='Human'

    #constructor
    def __init__(self, name, age):
        self.name = name
        self.age = age

    #Instance method
    def print_name_Age(self):
        print('Instance method execution')
        print('name={}, age={}'.format(self.name, self.age))

    #Class method
    @classmethod
    def print_class_name(cls, msg):
        print('Class method execution')
        print(cls.class_name)
        print(msg)

    #Static method
    @staticmethod
    def print_msg(msg):
        print('Static method execution')
        print(msg)

#Class method
Human.print_class_name('Hello')

#Instance method
human =Human('taro', 18)
human.print_name_Age()

#Static method
human.print_msg('static')
Class method execution
Human
Hello
Instance method execution
name=taro, age=18
Static method execution
static

Special method

A method that is called when you perform a specific operation when accessing an instance

Method Overview
__str__(self) str(),print()Called when you execute, and returns a string
__bool__(self) Customize the if statement comparison process
__len__(self) len()Customize the processing content of
__eq__(self、other) For the instance==Called when using an operator
__name__(self) Returns the name of the class
__hash__(self) Creates and returns a hash value from the passed value

reference

--Official document https://docs.python.org/ja/3.6/reference/datamodel.html#special-method-names

#Special method

class Human:

    #constructor
    def __init__(self, name, age, phone):
        self.name = name
        self.age = age
        self.phone = phone

    #Special method: print()Returns the following processing result when
    def __str__(self):
        return self.name + ":" + str(self.age)

    #Special method: "==Customize the content of the comparison process by
    """
When comparing instances, if name and phone match even if age is different
Returns True.
    """
    def __eq__(self, args):
        return (self.name == args.name) and (self.phone == args.phone)

man = Human('tanaka', 18, '090-9999-8888')
print(man)

woman = Human('tanaka', 20, '090-9999-8888')
print(man == woman)
#__str__Result of
tanaka:18

#__eq__If you have not defined
False

#__eq__If you have defined
True

Summary so far

#Unique exception
class CharaterAlreadyExistsException(Exception):
    pass

class AllCharacters:
    '''
Character information management class
    '''
    all_characters = []
    alive_characters = []
    dead_characters = []

    @classmethod
    def character_append(cls,name):
        #Same name returns unique error
        if name in cls.all_characters:
            raise CharaterAlreadyExistsException('Existing character name')

        cls.all_characters.append(name)
        cls.alive_characters.append(name)

    @classmethod
    def character_delete(cls,name):
        cls.dead_characters.append(name)
        cls.alive_characters.remove(name)

class Character:

    def __init__(self,name,hp,offense,defense):
        #Register character information in the constructor when creating an instance
         AllCharacters.character_append(name)
         self.name = name
         self.hp = hp
         self.offense = offense
         self.defense = defense

    def attack(self,enemy,critical=1):
        if self.hp <= 0:
            print('Character is Already dead.')
            return
        attack = self.offense - enemy.defense
        attack = 1 if attack <= 0 else attack
        enemy.hp -= (attack * critical)

        if enemy.hp <= 0:
            AllCharacters.character_delete(enemy.name)

    def critical(self, enemy):
        self.attack(enemy,2)

#----Application execution-----
chara_A = Character('A',10,5,3)
chara_B = Character('B',8,6,2)

print(chara_B.hp)
#chara_A.attack(chara_B)
chara_A.critical(chara_B)
print(chara_B.hp)

print(AllCharacters.alive_characters)
chara_A.critical(chara_B)
print(AllCharacters.dead_characters)
print(AllCharacters.alive_characters)
chara_B.attack(chara_A)
#Execution result
8
2
['A', 'B']
['B']
['A']
Character is Already dead.

Class inheritance

** Inheritance ** —— Inheriting the properties of another class. --The inheritance source is called a superclass, and the inheritance destination is called a subclass. --Subclasses can inherit superclass properties and methods.

** Polymorphism ** --In multiple created subclasses, create methods with the same name but different processing contents. --The property that can be called without worrying about the processing content when calling

override --By defining a method with the same name as the method defined in the parent class, you can rewrite the processing content unique to the subclass.

Overload --Define a method with the same name as the method defined in the parent class in the subclass. At this time, if the argument or return value is changed, it will be overloaded. --There is no overload feature in python. If you want to realize the same function as overload, you can respond to the change of the number of arguments by defining the required number of arguments with the default value None in the target method in advance.

#Parent class
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greeting(self):
        print('hello, {}'.format(self.name))

    def say_age(self):
        print('{} years old.'.format(self.age))

#Inherit the Person class
class Employee(Person):
    def __init__(self, name, age, number):

        #super()Call the constructor of the parent class using.
        super().__init__(name, age)

        #Since the values of the following properties are set in the constructor call of the parent class,
        #Subclass assignment to property is optional
        # self.name = name
        # self.age = age
        
        #Since number is a unique element of Employee class, it is assigned separately.
        self.number = number

    def say_number(self):
        print('my number is {}'.format(self.number))

    #Override parent class methods
    def greeting(self):
        #Execute the method with the same name in the parent class
        super().greeting()
        print('I\'m employee number = {}'.format(self.number))

    #Overload(A feature not found in python. Default argument can be substituted)
    # def greeting(self, age=None):
    #     print('Overload')

man = Employee('Tanaka', 34, 12345)
man.greeting()
man.say_age()
hello, Tanaka
I'm employee number = 12345
34 years old.

Multiple inheritance of classes

** Multiple inheritance ** Multiple classes can be inherited as parent classes.

class Class_A:

    def __init__(self, name):
        self.a_name = name

    def print_a(self):
        print('ClassA method running')
        print('a = {}'.format(self.a_name))

    def print_hi(self):
        print('{}, hi'.format(self.name))


class Class_B:

    def __init__(self, name):
        self.b_name = name

    def print_b(self):
        print('ClassB method running')
        print('b = {}'.format(self.b_name))

    def print_hi(self):
        print('{}, Hi!'.format(self.b_name))

#Subclasses that inherit multiple times
class NewClass(Class_A, Class_B):

    def __init__(self, a_name, b_name, name):
        Class_A.__init__(self, a_name)
        Class_B.__init__(self, b_name)
        self.name = name

    def print_new_name(self):
        print("name = {}".format(self.name))

    def print_hi(self):
        Class_A.print_hi(self)
        Class_B.print_hi(self)
        print('New Class hi')

sample = NewClass('A_Name','B_Name','New Class Name',)
#Execute inherited ClassA and ClassB methods
sample.print_a()
sample.print_b()

#Execute subclass-specific methods
sample.print_new_name()

#Execute superclass methods from subclasses
sample.print_hi()
ClassA method running
a = A_Name
ClassB method running
b = B_Name
name = New Class Name
New Class Name, hi
B_Name, Hi!
New Class hi

Polymorphism

When multiple subclasses are created, is the method with the same name always defined and can be executed?

** Abstract class ** --A class that does not (cannot) create an instance of the class itself, has an abstract method, and is inherited and used by subclasses as a superclass. --When creating an abstract class, it is necessary to set the metaclass "ABCmeta" of the abc library as the metaclass to the "metaclass" of the abstract class.

#Abstract class template
from abc import ABCMeta, abstractmethod

class Human(metaclass=ABCMeta)

    @abstractmethod
    def say_name(self, name):
        pass

** abstract method ** --A method created by declaring "@abstractmethod" directly above the method --If a class with an abstract method is a superclass, it is necessary to define a method that overrides the abstract method in the subclass.

#Abstract class
from abc import ABCMeta, abstractmethod

class Human(metaclass = ABCMeta):

    def __init__(self, name):
        self.name = name
    
    #Abstract method
    @abstractmethod
    def say_something(self):
        pass

    def say_name(self):
        print('my name is {}.'.format(self.name))

"""
If you inherit the abstract class as below@Declared as an abstract method
If you do not override the method, an error will occur when creating the instance.

class Woman(Human):
    pass

error:
TypeError: Can't instantiate abstract class Woman with abstract methods say_something
"""

class Woman(Human):
    def say_something(self):
        print('I\'m Lady.')

class Man(Human):
    #Add argument type with override
    def say_something(self, name='nameless', age='20'):
        print('I\'m Men.' + str(age))

#Abstract class execution
# wm = Woman('Hanako')
# me = Man("Yamada")
# wm.say_something()
# me.say_something('taro',12)

#Polymorphism
"""
It's not decided whether the human instance is Man or Woman until it is executed.
It doesn't matter whether the instance method to be executed is an instance of either class
Can be executed
"""
num = input('Please input 0 or 1: ')
human = ""
if num == '0':
    human = Woman(Human)
elif num == '1':
    human = Man(Human)
else:
    print('wrong number')

human.say_something()
--Check the execution result of the abstract class--
I'm Lady.
I'm Men.12

#If you enter 0
--Polymorphism execution result--
I'm Lady.

#If you enter 1
--Polymorphism execution result--
I'm Men.20

Private variables

--Variables that cannot be accessed from the outside (There is a way to access them in python) --Access is possible via class. However, it is rarely used. --When actually programming, you should basically define it with a private variable

__variable = "val"
#When trying to call a private variable
AttributeError: 'Human' object has no attribute '__name'
#Access private variables from your instance
val =instance._name of the class__name

Encapsulation, setter, getter

When using Private variables, it is necessary to encapsulate the Private variables so that they cannot be seen from outside the class.

#getter definition
def get_Variable name():
processing

#Definition of setter
def set_Variable name();
processing

#getter,Create a property to call setter
Variable name= property(get_Variable name, set_Variable name)

-A common name is entered in the "variable name" part.

** <Pattern 1> **

#Encapsulation, getter, setter pattern 1

class Human:
    def __init__(self,name,age):
        #private variable
        self.__name = name
        self.__age = age

    def get_name(self, name):
        print('call getter [name]')
        return self.__name

    def set_name(self, name):
        print('call setter [name]')
        self.__name = name

    #Creating a property (getter,Required to use setter)
    #Use property when accessing from the outside.
    name = property(get_name, set_name)

    def print_name(self):
        print(self.__name)

human = Human('Tanaka', 20)

#getter,Call properties like variables when using setter
human.name = 'Suzuki'
human.print_name()

** <Pattern 2 (mainly this)> **

#getter
@property 
def val_name(self):
return private variable

#setter
@val_name.setter
def val_name(self, val):
    self.__val = val
#Encapsulation, getter, setter pattern 2

class Human:

    def __init__(self, name, age):
        self.__name = name
        self.__age = age
    
    #getter definition
    @property
    def name(self):
        print('call getter [name]')
        return self.__name
    
    @name.setter
    def name(self, name):
        print('call setter [name]')
        self.__name = name

    @property
    def age(self):
        print('call getter [age]')
        return self.__age

    @age.setter
    def age(self, age):
        print('call setter [age]')
        if age >= 5:
            print('Please enter a value of 4 or less.')
            return
        else:
            self.__age = age
    
human = Human('taro', 24)
human.name = 'goro'
human.age = 5
print(human.name)
print(human.age)

Summary so far


#Library for abstract methods
from abc import abstractmethod, ABCMeta

#Abstract class definition
class Animals(metaclass=ABCMeta):

    #Encapsulation support(private variables, getters, setters)
    def __init__(self, voice):
        self.__voice = voice

    @property
    def voice(self):
        return self.__voice

    @voice.setter
    def voice(self, voice):
        self.__voice = voice

    #Abstract method(Must be overridden in subclass)
    @abstractmethod
    def speak(self, voice):
        pass

"""
Since the following subclass inherits Animals as a superclass,
Constructor processing, getter, setter are common
"""
class Dog(Animals):
    #self.voice uses getter processing defined in the superclass.
    def speak(self):
        print(self.voice)

class Cat(Animals):
    def speak(self):
        print(self.voice)

class Sheep(Animals):
    def speak(self):
        print(self.voice)

class Other(Animals):
    def speak(self):
        print(self.voice)


#Get standard input
select = int(input('Please enter a number: '))

if select == 1: #dog
    animal = Dog("Dog")
elif select == 2: #Cat
    animal = Cat("Meow")
elif select == 3: #sheep
    animal = Sheep("Baa")
else: #Other
    animal = Other("There is no such animal")

animal.speak()

File input

filepath = 'resources/test.txt'

"""
#open,Specify close(Better to use with for forgetting to close hat)
f = open(filepath, mode='r') #Open file in read mode
data = f.read() #Read the entire contents of the file
f.close()

print(data)
"""

#open,Close automatically
#Specify the character code of the file to be read with the encoding option
with open(filepath, mode='r', encoding='utf-8') as f:
    text = ''

    #Read only one line
    #print(f.readline())

    #Read line by line (return as an array)
    for line in f.readlines():
        text += line

    print(text)

File output

filepath = 'resources/output.txt'

"""
#Specify a newline character with the newline option. (Default:\n)
f = open(filepath, mode='w', encoding='utf-8', newline='\n')
f.write('Written')
"""

list_a = [
    ['A','B','C'],
    ['Ah','I','U']
    ]

#When using the with syntax mode:w overwrites the file with the same name if it exists.
with open(filepath, mode='w', encoding='utf-8', newline='\n') as f:
    f.writelines('\n'.join(list_a[0]))

#Output the file in append mode. If the specified file does not exist, create a new one.
with open(filepath, mode='a', encoding='utf-8', newline='\n') as f:
    f.writelines(list_a[1])

How to use with

with [class] as x:
processing

Before executing the process that describes with, execute the following process defined in the specified class.

In addition, the following processing is executed at the end of class processing.

When the process from the start to the end is continuously performed

--File writing process (file open-> write-> close) --Write data to DB (DB connection-> data registration-> DB disconnection

class WithTest:
    """
In order to make your own class a class that can be used with with, the following 3 methods must be implemented.
    """
    def __init__(self, file):
        print('init called')
        self.__file = file

    def __enter__(self):
        print('enter called')
        self.__file = open(self.__file, mode='w', encoding='utf-8')
        return self

    def __exit__(self, exc_type, exc_val, traceback):
        print('exit caled')

    def write(self, msg):
        self.__file.write(msg)

with WithTest('resources/output.txt') as wt:
    print('---Inside with--')
    wt.write("writing")
init called
enter called
---Inside with--
exit caled
kekosh-mbp:flaskenv kekosh$ 

Recommended Posts

SNS Python basics made with Flask
SNS Flask (Ajax) made with Flask
SNS Flask (Model) edition made with Flask
SNS made with Flask Flask (Blueprint, bcrypt)
Programming with Python Flask
SNS made with Flask Flask (login process by flask_login)
I made a Mattermost bot with Python (+ Flask)
I made blackjack with python!
Web application with Python + Flask ② ③
I made blackjack with Python.
Othello made with python (GUI-like)
I made wordcloud with Python.
Web application with Python + Flask ④
Python basics ⑤
Python basics
Python basics ④
[Python] Use Basic/Digest authentication with Flask
I made LINE-bot with Python + Flask + ngrok + LINE Messaging API
Numer0n with items made in Python
I made a simple book application with python + Flask ~ Introduction ~
I made a fortune with Python.
Getting Started with Python Basics of Python
Python basics ③
Python basics
Othello game development made with Python
Python basics
Python basics
Python basics ③
Python basics ②
Python basics ②
I made a daemon with Python
Application development with Docker + Python + Flask
I made a Nyanko tweet form with Python, Flask and Heroku
Basics of binarized image processing with Python
Simple Slack API client made with Python
HTTP split download guy made with Python
I made a character counter with Python
POST variously with Python and receive with Flask
Page cache in Python + Flask with Flask-Caching
Getting Started with Python for PHPer-Super Basics
Easy web app with Python + Flask + Heroku
[Python] Quickly create an API with Flask
I made a Hex map with Python
Serverless face recognition API made with Python
I made a roguelike game with Python
I made a simple blackjack with Python
I made a configuration file with Python
I made a neuron simulator with Python
Othello app (iOS app) made with Python (Kivy)
FizzBuzz with Python3
Python basics: list
Scraping with Python
Statistics with python
Scraping with Python
Python with Go
#Python basics (#matplotlib)
Twilio with Python
Python CGI basics
Python basics: dictionary
Integrate with Python
Play with 2016-Python