I'm a Java rar, so I started playing with Python, so make a note. Really just a note.
You can create a development environment in Eclipse. There is Pleiades All in One for Python, so please drop it.
You can create it by right-clicking Package Explorer → "New" → "Project" → "Pydev Project".
It seems that Python also has the concept of a package. You can create it by right-clicking Package Explorer → "New" → "Pydev Package".
Python source files are files with the extension py You can create it by right-clicking Package Explorer → "New" → "Pydev Module". You can select a class or main (execution) template.
Right-click the py file with the main method (?) → "Run" → "Run Python"
The publoc void main (String ... args)
-like thing in java is described as follows
if __name__ == '__main__':
print("I am a beginner")
ʻI am a beginner` appears on the console
Prepared by selecting the "main" template when creating a Pydev module from Eclipse
Python defines blocks with indentation.
if __name__ == '__main__':
print("1")
if True:
print("2") #in if
print("3") #in if
else:
print("4") #In else
print("5") #In else
print("6") #Exit the block
Is output as 1, 2, 3, 6
Substitution is the same as variable declaration.
i = 1
s = "String"
b = True
Use ʻand, ʻor
, not
If object is used in a conditional expression, it will be treated as "false" when it is None.
o = None
if not o:
print("o is None")
None is Python null (like)
If a character string is used in a conditional expression, it will be treated as "false" when it is blank.
s = ""
if not s:
print("s is blank")
If a numerical value is used in a conditional expression, it will be treated as "false" when it is 0.
i = 0
if not i:
print("i is 0")
If an array (etc.) is used in a conditional expression, it will be treated as "false" when it is empty.
a = []
if not a:
print("a is empty")
if I have already written a part of the if statement, but write it as follows
if condition 1:
print("Condition 1 is true")
elif condition 2:
print("Condition 1 is false")
print("Condition 2 is true")
else:
print("Condition 1 is false")
print("Condition 2 is false")
ʻElse if is written as ʻel if
.
for The for statement is described as follows.
for i in range(10):
print(i) #0 to 9 are output in order
for i in range(3, 7):
print(i) #3 to 6 are output in order
for i in range(1, 12, 2):
print(i) # 1,3,5,7,9,11 is output in order
for s in ["A", "B", "C"]:
print(s) #A, B and C are output in order
A Python for statement is like a Java extension for statement. It seems that for statements by index, escape conditions, increments, etc. are done well using range.
while The while statement works if you write it in the same atmosphere as before. It's so normal that I won't write an example. There is a while ... else syntax for some reason, but I don't know where to use it. .. ..
switch-case It seems that there is no such thing.
It is explained as "conditional expression" and "conditional operator" instead of the name of ternary operator.
http://docs.python.jp/3.5/reference/expressions.html#conditional-expressions
for i in range(10):
a = "odd number" if i % 2 else "even number" #The one called "conditional expression"
print(str(i) + " is an " + a)
list Create an instance with javascript glue
items1 = []
items2 = ["A", "B"]
Add or remove
items = ["A", "B"]
items.append("C") #Java List#add
items.extend(["D", "E", "F"]) #Java List#addAll
del items[4] #Java List#remove(int)
items.remove("F") #Java List#remove(Object)
size = len(items) #Java List#size
print("size:" + str(size)) # 4
index2 = items[2] #Java List#get
print("index2:" + index2) # C
idx = items.index(index2) #Java List#indexOf
print("idx:" + str(idx)) # 2
for item in items:
print(item) # A,B,C,Output D in order
items2 = items[:] #Create a copied list instance
print(items2) # ['A', 'B', 'C', 'D'](Containsthesameelementsasitems)
print(items is items2) #False (another instance)
items.insert(0, "INS") #Java List#add(int, Object)
print(items) # ['INS', 'A', 'B', 'C', 'D']
What is [:]
?
items3 = items[1:3] #List generation that extracts index 1 to 2
print(items3) # ['B', 'C']
items4 = items[1:] #List generation that extracts everything after index 1
print(items4) # ['B', 'C', 'D']
items5 = items[:3] #List generation that extracts everything before index 3
print(items5) # ['A', 'B', 'C']
There is a concept of iterator or "iterable". Similar to Java's Iterable class. "Iterable" can be turned with Python's for statement. The list is also "iterable", and the Python string (str) is also "iterable". It seems that you can make your own, but this time it is omitted.
There is also.
t = ("A") # tuple
print(type(t))
d = {"A" : 1} # dict
print(type(d))
s = {"A"} # set
print(type(s))
I haven't investigated the details. Reference below http://www.tohoho-web.com/python/list.html
It can be expressed in either single quotes or double quotes.
s1 = "I am a beginner"
s2 = 'I am a beginner'
I don't know which one is more common, but the feeling I'm looking for is double quotes?
There is also a technique of three quotes.
s = """Python
Oh python
Python"""
print(s)
result
Python
Oh python
Python
Use +
.
There is no implicit cast, so use the following.
Use str
.
i = 10
print("Numerical value to string" + str(i))
print("Concatenate strings and numbers" + i) #error
If you create a method called __str__
, it will be called when it is converted to a string.
The atmosphere of the role of the toString method in Java, where __str__
is (cannot be called directly).
It is defined by writing def.
#Method is defined by def
def method1():
print("foo")
#Arguments are written in parentheses
def method2(arg1, arg2):
print(arg1)
print(arg2)
#Return value is returned by return
def method3():
return "bar"
If you don't care, you can pass it normally, but there is also a strange way of passing (not in Java).
def method2(arg1, arg2):
print("---")
print(arg1)
print(arg2)
if __name__ == '__main__':
method2("A", "B") #Usual
method2(arg1="A", arg2="B") #You can also pass it like this (keyword argument)
method2(arg2="B", arg1="A") #In this case, it seems that the order may be random
method2(*["A", "B"]) #Pass in an array
method2(**{"arg2":"B", "arg1":"A"}) #Pass by dict
The results are all the same
Something like C ++.
#Arguments can define default values arg2 if there is one argument when calling"DefaultArg"Enter
def method4(arg1, arg2 = "DefaultArg"):
print("---")
print(arg1)
print(arg2)
if __name__ == '__main__':
method4("A", "B")
method4("A") #Use default for the second argument
result
---
A
B
---
A
DefaultArg
Assuming dict passing, it seems that the first argument can also be the default argument, but that seems impossible
def method5(arg1 = "DefaultArg", arg2):
print(arg1)
print(arg2)
SyntaxError
There is a method of accepting with tuple type and a method of accepting with dict type
# *Is a variadic argument that the tuple type accepts
def method_variadic_tuple(arg1, *others): #others is a tuple type variable length argument
print("---" )
print("First argument:" + arg1)
print("Variadic argument:" + str(others))
print("Variadic argument length:" + str(len(others)))
if __name__ == '__main__':
method_variadic_tuple("A")
method_variadic_tuple("A", "B")
method_variadic_tuple("A", "B", "C")
method_variadic_tuple("A", *("B", "C")) #It is also possible to pass it directly with tuple
method_variadic_tuple("A", *["B", "C"]) #list is also OK
method_variadic_tuple(*("A", "B", "C")) #All tuples can be handed over
result
---
First argument:A
Variadic argument:()
Variadic argument length:0
---
First argument:A
Variadic argument:('B',)
Variadic argument length:1
---
First argument:A
Variadic argument:('B', 'C')
Variadic argument length:2
---
First argument:A
Variadic argument:('B', 'C')
Variadic argument length:2
---
First argument:A
Variadic argument:('B', 'C')
Variadic argument length:2
---
First argument:A
Variadic argument:('B', 'C')
Variadic argument length:2
# **Is a variadic argument that is accepted as a dict type
def method_variadic_dict(arg1, **others): #others is a dict type variadic argument
print("---" )
print("First argument:" + arg1)
print("Variadic argument:" + str(others))
print("Variadic argument length:" + str(len(others)))
if __name__ == '__main__':
method_variadic_dict("A")
method_variadic_dict("A", d1="B") #dict variadic arguments pass like this
method_variadic_dict("A", d1="B", d2="C")
method_variadic_dict(arg1="A", d1="B", d2="C") #If you use the dict type, the first argument is also=The notation used is cleaner
method_variadic_dict(d1="B", arg1="A", d2="C") #In this case, the first argument is OK even in the middle
method_variadic_dict("A", **{"d1":"B", "d2":"C"}) #It is also possible to pass it directly with a dict
method_variadic_dict(**{"arg1":"A" , "d1":"B", "d2":"C"}) #The first argument can also be a dict.
# method_variadic_dict(*["A", {"d1":"B", "d2":"C"}]) #Is it really impossible to pass an array?
result
---
First argument:A
Variadic argument:{}
Variadic argument length:0
---
First argument:A
Variadic argument:{'d1': 'B'}
Variadic argument length:1
---
First argument:A
Variadic argument:{'d1': 'B', 'd2': 'C'}
Variadic argument length:2
---
First argument:A
Variadic argument:{'d1': 'B', 'd2': 'C'}
Variadic argument length:2
---
First argument:A
Variadic argument:{'d1': 'B', 'd2': 'C'}
Variadic argument length:2
---
First argument:A
Variadic argument:{'d1': 'B', 'd2': 'C'}
Variadic argument length:2
---
First argument:A
Variadic argument:{'d1': 'B', 'd2': 'C'}
Variadic argument length:2
Declare class class name (inheritance source)
.
If you use an Eclipse template, it will write as follows.
class MyClass(object):
'''
classdocs
'''
def __init__(self, params):
'''
Constructor
'''
__init__
As you can see from the comment (docstring) already, the constructor is defined by writing __init__
.
The argument self
is your instance, and write the parameters you want to accept in the constructor after it.
if __name__ == '__main__':
obj = MyClass("param") #argument"param"Generate MyClass with and assign it to obj
If the field variable is from inside the instance, you can create a variable by assigning it with self.field name
.
When from the outside, assign with variable that stores the instance.field name
normally.
The method is indented according to the class and defined with def
.
The first argument is self
(similar to __init __
).
When calling from the outside, give an argument without self
and call.
class MyClass(object):
def __init__(self, param):
self.field1 = "field1" # self.If you assign it to a field name, it becomes a field variable
print("init param:" + param)
def foo(self, param): #Instance method
self.field2 = "field2" #Field variables can be created at any time
print("foo param:" + param)
if __name__ == '__main__':
obj = MyClass("A")
print(obj.field1)
obj.foo("B")
print(obj.field2)
obj.field3 = "field3" #You can create field variables from outside
print(obj.field3)
result
init param:A
field1
foo param:B
field2
field3
Express by naming.
reference: http://docs.python.jp/3.5/reference/lexical_analysis.html#reserved-classes-of-identifiers http://docs.python.jp/3.5/tutorial/classes.html#tut-private
If you add two underscores to the head, it will be private.
(Strictly speaking, there is a way to access it, so it may not be called private.)
However, names with two underscores behind them, such as __hoge__
, are for Python systems, so don't give them a new name.
Also, as a habit, one underscore seems to be non-public.
class MyClass(object):
def foo(self): # public
print("foo" )
def _foo(self): #Non-public as a habit
print("_foo" )
def __foo(self): # private
print("__foo" )
def call_private_foo(self): # __Method to call foo
self.__foo() #Private methods can be called
if __name__ == '__main__':
obj = MyClass()
obj.foo()
obj._foo()
# obj.__foo() #Cannot be called
obj.call_private_foo()
obj._MyClass__foo() #Strictly speaking, there is a way to access it. "_It has been replaced with "class name + method name". However, it does not appear in the storage of Eclipse
result
foo
_foo
__foo
__foo
If you change the part written as (object)
to the class you want to inherit, you can inherit it for the time being.
It seems that multiple inheritance is possible, but I don't feel like I can master it, so I will omit it this time.
The constructor of the parent class is not called just by inheriting.
Call it by writing super (own class, self). Method name ()
as shown below.
class AbsMyClass(object):
def __init__(self):
print("AbsMyClass__init__Was called")
class MyClass(AbsMyClass):
def __init__(self):
super(MyClass, self).__init__() #Inheritance source__init__Call
print("MyClass__init__Was called")
if __name__ == '__main__':
obj = MyClass()
result
AbsMyClass__init__Was called
MyClass__init__Was called
You can avoid calling the parent class __init__
, the timing is arbitrary, you can call it as many times as you like, and there is no freedom.
I'm new to Python, so I often forget to write and am addicted to it.
Eclipse complements and writes. The syntax is omitted.
I wrote Python beginner memo (2).
Recommended Posts