point
point
Scope and namespace examples
def scope_test():
def do_local():
spam = "local spam"
def do_nonlocal():
nonlocal spam
spam = "nonlocal spam"
def do_global():
global spam
spam = "global spam"
spam = "test spam"
do_local()
print("After local assignment:", spam)
# After local assignment: test spam
do_nonlocal()
print("After nonlocal assignment:", spam)
# After nonlocal assignment: nonlocal spam
do_global()
print("After global assignment:", spam)
# After global assignment: nonlocal spam
scope_test()
print("In global scope:", spam)
# In global scope: global spam
Class definition
class className:
<Sentence 1>
.
.
.
<Sentence N>
point
point
MyClass.i
and MyClass.f
are valid in the following cases)Attribute reference
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'
Class instantiation
x = MyClass()
__init __ ()
method is defined, __init () __
will be called automatically for the newly created instance.__init__()function
def __init__(self):
self.data = []
__init __ ()
functionClass instantiation(With arguments)
class Human:
def __init__(self, height, weight):
self.height = height
self.weight = weight
x = Human(165, 55)
print('height:', x.height, 'weight:', x.weight)
# height: 165 weight: 55
point
Data attribute and method references
class MyClass:
def __init__(self):
pass
def f(self, word):
print(word)
x = MyClass()
#Add / reference data attributes
x.counter = 1 #Data attributes do not need to be declared in advance
while x.counter < 10:
x.counter = x.counter * 2
print(x.counter) # 16
del x.counter
#Method reference
x.f("hello kawauso")
Store method object in variable
xf = x.f
xf('hello kawauso again') #output: hello kawauso again
point
Examples of class and instance variables
class Dog:
kind = 'Shiba' #Class variables
def __init__(self, name):
self.name = name #Instance variables
taro = Dog('Taro')
jiro = Dog('Jiro')
#Reference to class variables
print(taro.kind) #Shiba
print(jiro.kind) #Shiba
#Instance variable reference
print(taro.name) #Taro
print(jiro.name) #Jiro
point
self
(not a reserved word, but everyone is used to it)point
Inheritance sample
class base():
def a(self):
print('I base.is a.base.Call b')
self.b()
def b(self):
print('I base.b.der.Overridden with b')
class der(base):
def b(self):
print('I der.b.')
b = base()
d = der()
b.a()
#I base.is a.base.Call b
#I base.b.der.Overridden with b
d.a()
#I base.is a.base.Call b
#I der.b.
point
Python allows class definition with multiple base classes
There seems to be volume, so I will summarize this separately
point
_
are private parts of the API__spam
with the form of _classname__spam
Name mandaring example
class Mapping:
def __init__(self, iterable):
self.items_list = []
self.__update(iterable)
def update(self, iterable):
for item in iterable:
self.items_list.append(item)
__update = update #↑ update()Private copy of method
class MappingSubclass(Mapping):
# update()While offering a new signature of
#Existing__init__()Can be used without destroying
def update(self, iterable):
for item in zip(keys, values):
self.items_list.append(item)
class Employee:
pass
john = Employee()
john.name = 'Jhon Doe'
john.dept = 'computer lab'
john.salary = 1000
read ()
or readline ()
method in a class that gets data from a string buffer, you can pass it as an argument to a function that receives and formats data from a file object.m ()
, the instance object is m.__self__
and the function object corresponding to the method is m.__ func__
.point
point
__next__ ()
, which throws a StopIteration
exception when the elements are exhausted, and the for loop ends in response.__iter__()When__next__()
# __next__()Returns an object with a method__iter__()Define a method
#Already__next()__In the class defined by__iter__()Just return self
class Reverse:
def __init__(self, data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def __next__(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]
rev = Reverse('spam')
iter(rev)
for char in rev:
print(char)
# m
# a
# p
# s
point
yield
in the part that returns data__iter__ ()
and __next__ ()
methods, so it's easy to generate iterators.Generator example
def reverse(data):
for index in range(len(data)-1, -1, -1):
yield data[index]
for char in reverse('golf'):
print(char)
# f
# l
# o
# g
point
()
to easily apply it.Generator expression example
sum(i*i for i in range(10)) #Squared total
xvec = [10, 20, 30]
yvec = [7, 5, 3]
sum(x*y for x,y in zip(xvec, yvec)) #inner product
from math import pi, sin
#sin table
sine_table = {x: sin(x*pi/180) for x in range(0, 91)}
#Unique words on the page
unique_words = set(word for line in page for word in line.split())
#Alumni president
valedictorian = max((student.gpa, student.name) for student in graduates)
data = 'golf'
list(data[i] for i in rage(len(data)-1, 1, -1))
Recommended Posts