Wecode day 3

Michael Minchang Kim·2020년 4월 22일
0

wecode

목록 보기
7/22
post-custom-banner

While Loops

Same as java but you can add an else statement.
The else statement runs if the conditional gets fullfilled.

while <조건문>:
    <수행할 문장1>     
    <수행할 문장2>     
    <수행할 문장3>     
    ...
    <수행할 문장N> 
else:
    <while문이 종료된  수행할 문장1>     
    <while문이 종료된  수행할 문장2>     
    <while문이 종료된  수행할 문장3>     
    ...
    <while문이 종료된  수행할 문장N>

Looping Dictionary

A normal loop using dictionaries return the key instead of the value

Looping Dictionary With Values Instead of Keys

Use the values() function to read the values.

Looping Dictionaries With Both Keys and Values

You can have 2 variables in a for loop and go through multiple lists. Use this concept to read both keys and values.
Use the items() function

Nested Functions

Functions can be nested in python.

Closure

Closure is when you shut out external forces interacting with variables within the parent function
the child function takes in the parent function's variable in and works on the value within itself keeping the original value intact
the parent function returns the value that the child function
the parent value can be used through the child function
more info

링크텍스트

Decorators

Decorators are funtions that "decorate" other functions.
For example, if you want a to count the number of times a function is called, you can create a decorator that does this.

def call_counter(func):
    def helper(x):
        helper.calls += 1
        return func(x)
    helper.calls = 0

    return helper

@call_counter
def succ(x):
    return x + 1

print(succ.calls)
for i in range(10):
    succ(i)
    
print(succ.calls)

--result--
0
10

For functions with multiple arguments.

def call_counter(func):
    def helper(*args, **kwargs):
        helper.calls += 1
        return func(*args, **kwargs)
    helper.calls = 0

    return helper

@call_counter
def succ(x):
    return x + 1

@call_counter
def mul1(x, y=1):
    return x*y + 1

print(succ.calls)
for i in range(10):
    succ(i)
mul1(3, 4)
mul1(4)
mul1(y=3, x=2)
    
print(succ.calls)
print(mul1.calls)
--result--
0
10
3

more info in link 링크텍스트

!!!don't confuse decorators and functions, when you are taking in arguments for a decorator the surrounding is the parent function and the decorator is the child function!!!!

Scope

using the example of nested functions of above

Local Scope -> child function
Enclosing Scopes(Nonlocal) -> parent function
Module Scope(Global) -> main
Builtin Scope -> the built in functions

Class

Classes are outlines of instances.
For example lets take a look at cars. Within the category of cars there are multiple different kinds. bmw, masserati, genesis are all cars.
In this case "cars" would be the class and bmw, maserati and genesis would be instances of the cars class.

attributes

Attributes are elements that the instances created through a class will all have.
In the example of cars, it would be Maker, Model Name, and Horse Power.
These attributes are defined through methods(functions within classes are called methods).

class Car:
    def __init__(self, maker, model, horse_power):
        self.maker       = maker
        self.model       = model
        self.horse_power = horse_power

Methods

all methods have to include the "self" argument

example class

class Database:
  def __init__(self, name, size):
    self.name = name
    self.size = size
    self.data = {}
  def insert(self,field,value):
    if len(self.data) < self.size:
      self.data[field] = value
  def select(self, field):
    if field in self.data:
      return self.data[field]
    else:
      return None
  def update(self, field, value):
    if field in self.data:
      self.data[field] = value
  def delete(self, field):
    if field in self.data:
      del self.data[field]

Modules and Packages

You can import variables and functions from external python files.
Modules are singular python files while Packets are folders with multiple python files.

module example

--main.py--

from my_module import my_func as f1, my_variable as v1

f1()
print(v1)

--my_module.py--

def my_func():
  print("importing test")
  
my_variable = 1

--result--

importing test
1

you can import entire modules as "something else" too

package example

import pkg.mod1
from pkg.mod2 import func2

pkg.mod1.func2()
func2()

packages have an initialzation file similar to that of a class

--init--

# __init__.py
from .mod1 import func2

--main--

# main.py
from pkg import func2

func2()

By importing to the __init__.py file you can forgo the dot notation for addressing.

# __init__.py
from .mod1 import func2
from .mod2 import func3

__all__ = ['func2', 'func3']

By allocating elements to the __all__ list you can control the
elements that can be imported from the package.
The default value of __all__ is all values within the package.

import other packages through pip

questions

1. sys.modules 와 sys.path의 차이점을 서술해 주세요.

sys.modules is a dictionary that contains all the modules and packages that are already imported. python saves them in a dict so that it doesnt have to search for them again whenever it's called

sys.path is a list that contains absolute paths that are related to python. Python goes through this list of paths to see if the module/package is located in those paths

--example sys.path--

[
	'/run_dir', 
	'/run_dir/customize', 
	'/usr/local/lib/python38.zip', 
	'/usr/local/lib/python3.8', 
	'/usr/local/lib/python3.8/lib-dynload', 
	'/home/runner/.local/share/virtualenvs/python3/lib/
	  python3.8/site-packages'
]

When python seaches for the address of a module or package, it goes through three options in the order of sys.modules -> built in modules -> sys.path

2. sys 도 import 해야하는 모듈입니다. 파이썬은 sys 모듈의 위치를 어떻게 찾을 수 있을까요?

sys is a module that is already built in. Since it is built in, python can easily access the sys module.

3. Absolute path와 relative path의 차이점을 서술해 주세요.

Absolute pathing is a path that is explicit and called from any positon within the project. Since it trickles down from the highest order directory it is absolute and does not change. The disadvantage is that it can get very long since it has to include every directory from the very top.

Relative pathing is a path that is relative to the current position of the file in the directory. This allows for a shorter lenth since you can omit the higher order directories. This pathing is used when accessing a local subpackage within a package. One dot refers to the current directory and two dots refer to the parent directory.

profile
Soon to be the world's Best programmer ;)
post-custom-banner

0개의 댓글