Python class (Python learning memo ⑦)

About scopes and namespaces

Namespace

point

scope

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 definition syntax

Class definition


class className:
    <Sentence 1>
    .
    .
    .
    <Sentence N>

point

Class object

point

Attribute reference


class MyClass:
    """A simple example class"""
    i = 12345
    def f(self):
        return 'hello world'

Class instantiation


x = MyClass()

__init__()function


    def __init__(self):
        self.data = []

Class 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

Instance object

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")

Method object

Store method object in variable


xf = x.f
xf('hello kawauso again') #output: hello kawauso again

Class variables and instance variables

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

Various other

point

Inheritance

Class inheritance

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.

Multiple inheritance

point

Private variables

point

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)

Other things

class Employee:
    pass

john = Employee()

john.name = 'Jhon Doe'
john.dept = 'computer lab'
john.salary = 1000

Exceptions are also classes

point

Iterator

point

__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

generator

point

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

Generator type

point

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

Python class (Python learning memo ⑦)
Python module (Python learning memo ④)
[Learning memo] Basics of class by python
Python exception handling (Python learning memo ⑥)
Python memo
python memo
Python memo
python memo
python learning
Python memo
Python memo
Python memo
Input / output with Python (Python learning memo ⑤)
Interval scheduling learning memo ~ by python ~
"Scraping & machine learning with Python" Learning memo
[Python] Memo dictionary
LPIC201 learning memo
[Python] class, instance
[Python] Learning Note 1
"Kanrika" python class
python beginner memo (9.2-10)
Python learning notes
Django Learning Memo
About python, class
python beginner memo (9.1)
python learning output
Python learning site
★ Memo ★ Python Iroha
Python learning day 4
[Python] EDA memo
Python Deep Learning
Python 3 operator memo
Python learning (supplement)
Deep learning × Python
[Memo] Machine learning
[My memo] python
Python3 metaclass memo
Python class, instance
[Python] Basemap memo
Python beginner memo (2)
python learning notes
#Python basics (class)
[Python] Numpy memo
Python & Machine Learning Study Memo: Environment Preparation
Python numbers, strings, list types (Python learning memo ①)
Python data structure and operation (Python learning memo ③)
Python standard library: second half (Python learning memo ⑨)
Python & Machine Learning Study Memo ③: Neural Network
Python & Machine Learning Study Memo ④: Machine Learning by Backpropagation
Python & Machine Learning Study Memo ⑥: Number Recognition
Python standard library: First half (Python learning memo ⑧)
python syslog wrapper class
My python environment memo
"Deep Learning from scratch" Self-study memo (9) MultiLayerNet class
Learning Python with ChemTHEATER 03
python openCV installation (memo)
"Object-oriented" learning with python
case class in python
Reinforcement learning 1 Python installation
Learning Python with ChemTHEATER 05-1
Python: Deep Learning Practices