A. It's the hottest language right now, and I feel that it's probably impossible for me to fully master machine learning, AI, deep learning, etc., but it's a scale of things to do. After all, I felt that I wanted to learn something that was popular to some extent (including the meaning of knowing why it was popular). However, this is just a matter of interest, and I wonder if I am learning a new language now, even if I stopped using PHP (Laravel), which I had been learning as a main line in the first place. This is because I saw Saku731-san's Such a project on Twitter. Based on my experience of learning PHP (Laravel) on my own and completing one deliverable from requirement definition to implementation
** What kind of service should I make ** ** What is better about this kind of processing? ** ** ** What kind of relationship do other people have with database design? ** ** ** What about security? What about refactoring? What is the transaction? ** **
I ran into a wall with various things along the way with etc, and in the end I didn't have to worry about compromising or writing code that wasn't very good. Of course, the issues that I learned from doing it and the things that I have to do from now on can be clearly seen, and probably even if I study with reference books etc., I will do things like 1 to Laravel textbooks in order ... Rather than doing it, at this stage of developing by actually using the framework, I think that it will be more efficient to scan the PHP framework Laravel introduction and PU where it is insufficient. I am. During this time, I actually checked what it was like at a bookstore, but it came out that something unexpected was written. I haven't changed because I don't have enough money because I'm job hunting ... However, in the end, such individual brush-ups can be done as much as you want by fishing the sea on the Internet for about 3000 yen at Techpit in this era, but now I am actually finding a job as an inexperienced engineer. While I'm job hunting, I don't think that kind of experience comes in handy, though it's several times better than nothing. It's like an "education" filter in normal job hunting. Companies also pay not cheap costs for hiring, so I learned from the beginning that it is common sense that about 30 to 60% of the annual income of a person who is appointed via an agent is taken as a margin. Under such circumstances, there is no merit to take a person who does not even have experience as a member of society and who does not have "experience of closing a project in actual work = production level coding and development experience" in the middle. After all, after paying for hiring, you have to invest in education. When it comes to taking such human resources, you have to feel the potential of those human resources and anticipate them, or you want to take such human resources and educate them in-house, or you have the physical strength to educate them, or you have to be inexperienced. It's clearer than looking at the fire that there are two choices, such as super black. It makes me sad to say it myself, but I'm currently crying and looking for a job because it's a true theory. By the way, I feel like I'm going to the latter.
Quiet talk, well, with such a background, when I finally remembered the limit of "self-study development", I was fortunate to see the above-mentioned project.
Background of launching the project: Even if I want to change jobs or move to another department and study programming, there are many things that I cannot get a chance without practical experience. However, if there is material to persuade the surroundings (= service that actually works), you can receive the same evaluation as "work experience". I would like to create a place where those who have studied hard so far can obtain "actually working services" and "team development experience" without risk. This is the background to the launch of the project. All you need is "the will to change your life with programming."
I wonder if I can read the planning intention and give me the experience I am looking for now. I thought, and when I inquired, at least, even if I was inexperienced, if I could write while examining Bootstrap and Python, it was OK to participate (however, at the minimum), so I started learning Python at this opportunity. It is the background of. Actually, it is a line to brush up PHP (Laravel), and since it is okay to make a deliverable and clone it, I would like to do it as a practice to make more and more apps, but I'd like to do it. The question of whether to leave a certain interest as it is and above all ** There is a place where you can get "actual service" and "team development experience" without risk **, but you can pass it through. I just couldn't do it. I don't think it's okay to think that it's just a shift, but I hope you can understand at the beginning that you have a solid sense of purpose.
I have made something like this to some extent
I understand the basics of function / class / database design in PHP-somewhat advanced, and although it is difficult to write by myself, do you feel that you can understand what is written? Is it about whether beginners will graduate and step into a complete PHP intermediate from beginner to intermediate PHP? I think. After all, it's still paper.
For the time being, I want to finish the tutorial of Django at the level where I can do what I have done with PHP with Python by May, so I will output roughly what I have done in a little over a month as a review. I will continue. I don't know what the level of participants will be, but I'm definitely at the bottom, and I think it's an implementation part as a role to be assigned, but I can contribute without burdening the team as much as possible. I want to be, so I want to do my best. On the contrary, this experience may be able to reduce to PHP. This time, I will list the basic parts of the basics of Python.
At the moment, what I think is the most different from PHP is the mechanism of import and module.
A module is a file in which functions and classes are written together in Python, and is like a so-called library.
Of course, some are built-in and you can make your own.
Also, the directory containing the module and the __init__.py
file is called a package.
You can write initialization code in __init__.py
.
There is also a mechanism called a namespace package that does not include __init__.py
, but here it is important to understand that a package is like this.
I guess it's similar to how namespaces work in PHP and Laravel.
As an actual usage
python
import datetime
#Or
from datetime import datetime, timedelta, timezone
Write like this.
When importing multiple modules, separate them with commas as in the latter example.
The former imports the module as a module type object.
By doing this, you can use the functions and variables defined in the module such as module name.function name
and module name.variable name
.
The latter can go a step further and directly import the module's objects individually.
Therefore, the former means that the entire datetime module is imported, and the latter means that only the datetime object, timedelta object, and timezone object of the datetime module are imported.
By the way, the datetime module is a module that can handle date and time in Python.
python
import random
number = random.randint(1,3)*100
print("Your score is" + str(nunmber) + "Is the point")
if number == 300:
print("Congrats")
else:
print("Off")
The above example is the one that imported the random module and wrote the conditional branching process based on it using the randint function. The randint function is a function that returns an arbitrary value from the specified argument range, multiplies it by 100, assigns it to the number variable, converts it to a character string with str, and outputs it. In PHP, the if statement is expressed in the form of ʻif (conditional expression) {} `, but in Python, the {} part is expressed by raising or lowering the intend. You don't need semicolons in PHP, but be sure to add a colon to conditional statements.
python
for i in range(0,16):
print(str(i))
#In the case of while
i = 0
while i <= 5:
print(str(i))
i = i + 1 #Advance counter variable
Arrays are called lists in Python.
python
#list
monster = ['Slime','Wolf','zombie','vampire','ghost']
#Add element to end of list
monster.append('Golem')
print(monster)
##Output result
['Slime','Wolf','zombie','vampire','ghost','Golem']
#Delete list element
monster = ['Slime','Wolf','zombie','vampire','ghost']
monster.pop(1) #Specify index
print(monster)
##Output result
['Slime','zombie','vampire','ghost']
#Repeat list
numbers = [12,34,56,78,90]
total = 0
for num in range(0,len(numbers))
total = total + numbers[nums]
print(total)
##Output result
270
#Divide and list elements
team_str = "Brave,Warrior,Ninja,Wizard"
print(team_str.split(","))
##Output result
['Brave', 'Warrior', 'Ninja', 'Wizard']
str = "One cold rainy day when my father was a little boy he met an old alley cat on his street"
print(len(str.split(" ")))
##Output result
20 #You have counted the number of elements that have been split and listed, in this case how many words there are.
url_str = input().rstrip()(Input is https://www.yahoo.co.jp/If it was an example)
print(url_str.split("/"))
##Output result
['https:', '', 'www.yahoo.co.jp', 'example']
len () is a function that returns the number of characters and elements. A function that separates character strings etc. with the symbol specified in the argument with str.split () and stores it in a list.
A dictionary is a key: value
relationship, that is, a list that stores properties, and is a so-called associative array.
python
#Dictionary representation
{'red':'apple','blue':'sea','green':'leaf','yellow':'lemon'}
#Remove element from dictionary
enemies = {"Zako":"Slime", "Medium boss":"Dragon", "Las boss":"Devil"}
del enemies['Zako'] #Specify key
→enemies = { "Medium boss":"Dragon", "Las boss":"Devil"}
#Dictionary loop(*1)
enemies = {"Zako":"Slime", "Medium boss":"Dragon", "Las boss":"Devil"}
for rank in enemies:
print(enemies[rank])
##Output result
Slime
Dragon
Devil
#When looping keys and values at the same time(*2)
for(rank,enemy) in enemies.items():
print(str(rank) + 'Is' + str(enemy) + 'is')
#Get the index at the same time in the list loop
team = ['Brave','Warrior','Wizard',]
for(i,person) in enumerate(team):
print(str(i+1) + 'Second' + person) #i is the index and person is the element.
##Output result
Zako is slime
The middle boss is a dragon
Las Boss is the Demon King
As you can see, unlike PHP, Python's for statement does not define a separate counter variable like for (i = 0; i <10; i ++)
, but like a foreach statement, such as a list or dictionary. The elements of the object of are assigned to variables in order and processing is performed.
If you look at * 1 and * 2 in the above example, you can see what kind of processing is being performed.
In other words, in the case of * 1, the elements in enemies are assigned to the rank variable one by one, and the processing is performed where the intensity is lowered, but in the case of the dictionary, it is assigned to the rank variable at this time. Since it is the key part, the output result is as described above.
In the case of * 2, by specifying two variables after for, rank → key and enemy → value are assigned respectively and looped at the same time.
Don't forget to use ʻitems () when you want to assign a value to a variable. I don't want to be confused here. ʻItems ()
is used to get the key and value of an element at the same time in a dictionary, or only the value, but ʻenumerate ()` is just an element such as a list and an index ( The order in which the list is stored) is acquired at the same time.
python
#list
apples = [1,100,1000,10000]
print(sorted(apples))
##Output result
[1, 100, 1000, 10000]
example = ['1.apple','4.apple','3.lemon','2.apple']
print(sorted(example))
##Output result
['1.apple','2.apple','3.lemon','4.apple']
## reverse=If True is specified, the items will be sorted in reverse order.
print(sorted(example, reverse=True))
##Output result
['4.apple', '3.lemon', '2.apple', '1.apple']
#dictionary
japan = {"kanagawa" : 10, "osaka" : 20, "okinawa":30}
print(sorted(japan))
##Output result
['kanagawa', 'okinawa', 'osaka']
##Output the value together
If you want to output the value together
print(sorted(japan.items()))
##Output result
[('kanagawa', 10), ('okinawa', 30), ('osaka', 20)]
In the case of numerical values, they are sorted in alphabetical order for alphabetic characters, and in alphabetical order for katakana and hiragana. However, in the case of Kanji, the order is the character code, not the reading order. The priority is number> string.
python
#Try to regenerate the list with for.
team = ['Brave','Warrior','Wizard',]
newteam= []
for person in team:
newteam.append('10 years later' + person)
print(newteam)
##Output result
['Hero 10 years later', 'Warrior 10 years later', 'Wizard 10 years later']
#Advanced version
numbers = [i*2 for i in range(10)]
print(numbers)
##Output result
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
##Let's apply it further
numbers2 = [[1 for i in range(3)] for j in range(4)]
print(numbers2)
##Output result
[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]
To simply create a list, store the element in []
and assign it to a variable.
As mentioned above, the list can be regenerated by storing another list in an empty list of another variable using the for statement.
For the applied part, a method of expanding a for statement with []
at the stage of assigning to a variable and creating a list by generating elements of the list there.
As a mechanism, it is [element for i in range ()]
that you want to store repeatedly.
In other words, the element specified before for is repeatedly stored in the list by the amount of range, so in this case range (10) = 0 to 9 is assigned to i, and the value doubled is the value. Since it will be repeatedly stored in the list as an element, the output result will be as shown above.
And if you apply it further, you can make a two-dimensional list.
The mechanism is [[element for i in range () for j in range ()]]
, and the part of for j in range ()
makes the list specified before for. It means that.
It may be useful when you want to make a simple list of numbers.
Even in Python, for statements can be nested.
python
letters = [[[0,0,1,1,0,0],
[0,1,0,0,1,0],
[1,0,0,0,0,1],
[1,1,1,1,1,1],
[1,0,0,0,0,1],
[1,0,0,0,0,1]],
[[1,1,1,1,1,0],
[1,0,0,0,0,1],
[1,1,1,1,1,0],
[1,0,0,0,0,1],
[1,0,0,0,0,1],
[1,1,1,1,1,0]],
[[0,1,1,1,1,0],
[1,0,0,0,0,1],
[1,0,0,0,0,0],
[1,0,0,0,0,0],
[1,0,0,0,0,1],
[0,1,1,1,1,0]]]
for i in letters: #Repeat the process below
for line in i: #Repeat the process below
for dot in line: #Processing to change to dot
if dot == 1:
print('@',end='')
else:
print(' ',end='')
print()
print() #Line breaks at every 2-digit index of the list.
This example is a process for converting 0 or 1 to the corresponding symbol using a cubic list to create a pixel art. First. Performs the process of converting 0 or 1 to dots (corresponding symbols or half-width spaces). And do that with each primary list in the list. Also, since the primary list is stored in each secondary list, the process is to start a new line after performing each secondary list.
A variadic argument is an argument when * is added to the argument when the number of arguments is unknown, or ** is added when the property is to be used as an argument. For example, in the following cases
python
def introduce(**people):
for name, greeting in people.items():
print("I" + name + "is." + greeting)
introduce(hero = "Nice to meet you", villager = "Hello", soldier = "Thank you")
##Output result
For example, in the above function, suppose you want to change the way of greeting depending on the job title with the argument that was done by people.
Then, since it is convenient to make the argument to be set indefinite, use a variable length argument.
In this case, we want to use the property as an argument, so set it to ** people
.
Then, people = [hero: 'Nice to meet you', villager: 'Hello', soldier: 'Thank you' 'because
it is possible to set the argument as such, the argument when calling the function after this It means that you should do it like this.
python
#function
def say_hello():
print('hello' )
say_hello()
##Output result
hello
#class
class Greeting:
def __init__(self, name):#Writing a constructor in Python
self.name = name
def say_hello(self):
print('hello' + self.name)
##Calling a class
test = Greeting('world')
test.say_hello()
##result
hello world
The processing content of the function is defined as def function name ():
and the content is lowered from there.
It's easy not to write {}.
In the case of a class, in addition to this, define the function as a method with class class name
.
The calling method is the same as PHP, and you can assign it to a variable and make it an object.
Also, self
is an instance of itself in a class, such as $ this
and self ::
in PHP.
In other words, self.name
is accessing the property (value of name) of the class.
For example, when the default value is set in the argument as shown below in the constructor part, the argument is not set in the class in the call.
python
def __init__(self, name='unknown'):
##Output result
hello unknown
It turns out that. When I actually use the class
python
class Item:
tax = 1.08
def __init__(self, price, quantity):
self.price = price
self.quantity = quantity
def total(self):
return int(self.price * self.quantity * Item.tax)
apple = Item(120,15) #Since two arguments are set in the constructor, specify the equivalent.
total = apple.total() #Method call
print(total)
##Output result
1944
It will be like this.
From the conclusion, the document explains as follows.
There are no "private" instance variables in Python that can only be accessed from within an object.
However, it can be treated as a pseudo by prefixing the variable or method with __
.
Let's look at the following example.
python
class Player:
def __init__(self, job, weapon):
self.job = job
self.__weapon = weapon
def walk(self):
print(self.job + 'Is adventuring in the wilderness')
def __attack(self, enemy):
print(self.__weapon + "so" + enemy + "To attack")
player1 = Player('Fighter','Sword')
player1.walk()
player1.attack('Golem') # error
print(player1.__weapon) # error
#Access private methods from the outside.
class Greeting:
def __init__(self):
self.msg = 'hello'
self.target = 'paiza'
def say_hello(self):
print(self.msg + " " + self.target)
def __say_yeah(self):
print("YEAH YEAH YEAH")
player = Greeting()
player.say_hello()
player._Greeting__say_yeah() #By doing this, the private method is called from outside the class.
First, if you look at the properties set in the constructor, you can see that the job property is public and the weapon property is private.
Therefore, print (player1.__weapon)
cannot access the weapon
property, resulting in an error.
The same reasoning applies to the method.
Since it is not preferable to access the property from the outside, it is basically better to keep it private.
On the other hand, if you really want to use a method but you can't call it from the outside, it's not a story, so don't make it private easily.
If you really want to access private methods from the outside
You can access it with the description variable to which the object is assigned._class name__private method name ()
.
python
class Box: #1
def __init__(self, item):
self.item = item
def open(self):
print("I opened the treasure chest." + self.item + "Got" +)
class ArmsBox(Box): #2
def look(self):
print("Master Sword stands quietly ...")
box = Box("Medicinal herbs")
box.open()
armsbox = ArmsBox('Bow and arrow of light') #3
armsbox.look()
armsbox.open()
##Output result
I opened the treasure chest. Got a medicinal herb
Master Sword stands quietly ...
I opened the treasure chest. Got a bow and arrow of light
#Method override
class Box:
def __init__(self, item):
self.item = item
def open(self):
print("I opened the treasure chest." + self.item + "Got" )
class ArmsBox(Box):
def open(self):
print("Generated a weapon" + "self.item" + "Got")
##When overriding, add an argument with a default value
class ArmsBox(Box):
def open(self, skill):
print("Generated a weapon." + self.item + "Got it." + self.item + "Weapon skills" + '\"' + skill + '\"' + "Is attached!")
armsbox = ArmsBox('Hagane sword')
armsbox.open('Deadly')
##Output result
I opened the treasure chest. Got a medicinal herb
Generated a weapon. Got a hand sword. Weapon skills for swords"Deadly"Is attached!
#Execute the method of the parent class as it is instead of referencing it
class Greeting:
def __init__(self):
self.msg = "hello"
self.target = "paiza"
def say_hello(self):
print(self.msg + " " + self.target)
class Hello(Greeting):
def say_hello(self):
super().say_hello() #Parent class say_Call the hello method.
print("YEAH YEAH YEAH")
player = Hello()
player.say_hello()
First, define the parent class (superclass) as in # 1. This time, we will use the constructor function to define the initial value and the function using it.
Next, create a child class that inherits the parent class in # 2 (subclass).
This time, define a function that outputs an arbitrary message with the print function.
After that, call it like # 3 and use it.
When inheriting a class, the child class can also refer to the method of the parent class, so the output will be as above.
Also, unlike PHP, Python class inheritance is defined by specifying the parent class as a class argument.
class Parent class name (child class name):
You can also override methods normally. The important thing is that Python overrides don't have to have the same argument and return types. Therefore, in the above example, there is no problem even if you inherit the Box class to ArmsBox and add an argument when overriding the open method.
If you want to use the method of the parent class directly instead of inheriting it, use super (). The method name of the parent class you want to use ()
.
python
class Player:
__charactor_count = 0
Since class variables are common variables in the class, it is a problem if they are accessed from the outside and modified unnecessarily, so it is better to keep them private.
Of course there are class variables, so of course there are class methods, but it's a little different from PHP. In PHP, static was specified before the method, and the call was made with self :: method name etc. For Python
python
class Player:
__charactor_count = 0
@classmethod #Decorator
def summary(cls):
print(str(Player.__charactor_count) + "Attacked slime with a person")
First, a technique called a decorator is used.
Decorators are a mechanism that allows you to add new functionality to a function that has already been defined.
Some are existing, and you can make your own.
This time @ classmethod
is prepared.
When used, the method argument is cls (= class itself)
instead of self (= instance itself)
.
By the way, there is also a @static method
related to this.
Use @ classmethod
to access class variables or change the behavior of inherited classes.
@staticmethod
is used when the operation does not change even at the inheritance destination.
In this case, we use @classmethod because we have to access the class variable.
By the way, the time when the behavior should change is as follows.
python
class Student:
def __init__(self, name, school):
self.name = name
self.school = school
self.marks = []
def average(self):
"""Return average grade
I want to access an instance variable, so I use the instance method.
"""
return sum(self.marks) / len(self.marks)
@classmethod
def friend(cls, origin, friend_name, *args):
"""Add friends from the same school.
Behavior should change in inherited class(Inherited class has salary property)
So use the class method.
The initialization argument of the child class is*Good to receive at args
"""
return cls(friend_name, origin.school, *args)
@staticmethod
def say_hello():
"""Say hello to the teacher
Use static method because the same behavior can be used even if inherited
"""
print("Hello Teacher!")
class WorkingStudent(Student):
def __init__(self, name, school, salary):
super().__init__(name, school)
self.salary = salary
hiro = WorkingStudent("Hiro", "Stanford", 20.00)
mitsu = WorkingStudent.friend(hiro, "Mitsu", 15.00)
print(mitsu.salary)
In the parent class, only name and school have properties, but in the inherited child class, the salary property is newly added, so the behavior will change. By the way, * args means to receive arbitrary variable length arguments as tuples (constant list). And if an argument is set before this * args, properties other than that argument will be grouped into a tap. In other words, in this case, hiro and "Mitsu" corresponding to origin and friend_name are used as arguments, but name and scholl among the initialization arguments of the child class are hiro = WorkingStudent ("Hiro", "Stanford", 20.00). ), Which is used as an argument in mitsu = WorkingStudent.friend, so it cannot be summarized in a tuple, Because self.salary = salary floats as an argument of def friend (). You will receive it in * args. As an aside, if you look closely, you can see that there is no problem even if you override the constructor method of the parent class and add an argument.
Quiet talk, that is, the following processing is possible.
python
class Player:
__charactor_count = 0
@classmethod
def summary(cls):
print(str(Player.__charactor_count) + "A person attacked slime.")
def __init__(self, name):
self.name = name
Player.__charactor_count += 1
print(str(Player.__charactor_count) + "Second player," + self.name + "Has appeared.")
def attack(self, enemy):
print(self.name + "Is" + enemy + "Attacked!")
class Wizard(Player):
def __init__(self):
super().__init__("Wizard")
def attack(self, enemy):
self.__spell()
print(self.name + "Is" + enemy + "Fired a flame!")
def __spell(self):
print("Zuban!")
print("===Fight slime at a party===")
hero = Player("Brave")
warrior = Player("Warrior")
wizard = Wizard()
party = [hero, warrior, wizard]
for member in party:
member.attack("Slime")
Player.summary()
##Output result
===Fight slime at a party===
The first player, the brave, has arrived.
The second player, the warrior, has arrived.
A third player, the Wizard, has arrived.
The brave attacked slime!
The warrior attacked slime!
Zuban!
The wizard set fire to slime!
Three people attacked slime.
python
try:
except exception name as e:
finally:
The process executed by the try block, the process when the exception block corresponds to the exception name (exception catching part), and the finally block are the processes executed even if the exception is ignored. In other words
python
try:
number = 0
print('This is 0')
print(number / 2)
except ZeroDivisionError as e:
print(e)
finally:
print('Try to see if there are any exceptions')
In the case of the syntax, 0 is first assigned to the number variable in the try block. After that, a message is output in the first print, but an exception occurs because the second print divides by 0. Therefore, the exception is thrown to the except block, it is caught, and the error message is assigned to the variable e and output. Finally, the finally block processing is executed. Of course, the variable e in the except block means that the error message is taken as an argument.
print ('Division of zero has occurred, processing will be aborted')
It can be replaced with any message such as.
By the way, if you ʻimport the
tracebackand
sys modules, you can write
sys.stderr.write () instead of
print. This allows you to define an error message in standard error output, and you can replace the error message on the error log side with any one. On the contrary, if you want to output the message on the error log side to the person who outputs to the screen in the same way as outputting with
print, use
print (traceback.format_exc ()) `.
It is also possible to define multiple except blocks to catch multiple exceptions.
In other words
python
except Exception as e:
except ZeroDivisionError as e:
except NameError as e:
If you define, exception checking will be performed in order from the top.
However, since the ʻExceptionclass corresponds to the parent class for the following two classes, when defining it, it must be described at the beginning and the exception class of the child class must be defined in the lower layer. In this case, if an exception other than
ZeroDivisionError and
NameError has occurred, the ʻException
class will catch
it, and the exceptions related to division of zero and specification of undefined variables will be the class here. It becomes a process of being throw
ed to.
python
ZeroDivisionError
#Exception in division of 0
NameError
#Exception to be passed when calling an undefined variable
You can make your own, but of course there are many that are provided as standard, so you should check and implement as appropriate when throwing exceptions.
raise exception class name ()
With this, it is possible to raise an exception of any exception class, and then catch it with the corresponding exception class. You can also specify a message as an argument.
Recommended Posts