1 of 35

챗GPT로 코딩하기

[강의교안 이용 안내]

  • 본 강의교안의 저작권은 양재삼한빛아카데미㈜에 있습니다.
  • 이 자료를 무단으로 전제하거나 배포할 경우 저작권법 136조에 의거하여 벌금에 처할 수 있고 �이를 병과(倂科)할 수도 있습니다.

마이크로파이썬을 활용한 사물인터넷

2 of 35

Chapter

05

함수와 클래스 만들기

3 of 35

index

5.1​

function

class

5.2

Type hints and function documentation

5. 3

module

5. 4

3/35

4 of 35

Learning Objectives

  • The function Create and Using Learn how .
  • of the class Concept and object orientation I understand programming (OOP) .
  • Reuse possible module Manufacturing and Installation Learn how .

4/35

5 of 35

detail outline

  • of the function Definition , parameters , and return values
  • class Definition , instance Creation , inheritance, and the super() function
  • Type Hints and docstrings Through cord Documentation
  • module Creation and MicroPython On the device Module / Main program installation

5/35

6 of 35

5.1 Functions

7 of 35

1. Defining a function

5.1 Functions

What is a function?

  • A bundle of code that performs a specific function
  • Increase code reusability and maintainability

How to define a function:

  • def function name (parameters):
  • Write function body with indentation
  • Return the result with the return keyword (can be omitted if not present)

Example introduction:

  • Function without parameters
  • Functions with parameters
  • Functions with return values
  • Functions that use default parameter values

7/35

8 of 35

1. Defining a function

5.1 Functions

function Definition (1): The parameter is no function

Example cord

Main point

def say_hello():

print("Hello, MicroPython!") say_hello() # Print: Hello, MicroPython!

  • Defining a function without parameters
  • Same result output when called

8/35

9 of 35

1. Defining a function

5.1 Functions

function Definition (2): Parameters present function

Example code:

def greet(name): print(f"Hello, {name}!") greet("Gildong") # Print: Hello, Gildong!

f-string description:

  • Automatically substitute variable values within curly brackets by adding f in front of the string
  • Readability and convenience growth

9/35

10 of 35

1. Defining a function

5.1 Functions

function Definition (3): The return value is present function

Example Code :

def add(a, b): return a + b result = add(3, 5) print(result) # output: 8

Main Points :

  • The result of the operation can be returned and stored in a variable.

addition function :

  • Returns multiple values separated by commas possible

10/35

11 of 35

1. Defining a function

5.1 Functions

function Definition (4): Parameters Default use

1

Example Code :

def greet(name="MicroPython"): print(f"Hello, {name}!") greet() # Prints: Hello, MicroPython! greet("Bob") # Prints: Hello, Bob!

2

arguments are omitted :

Use default values

3

passing arguments :

Override default

11/35

12 of 35

2. Location With the argument Keywords factor

5.1 Functions

location factor

Keywords factor

Mapping according to the order of arguments when calling a function

def print_info(name, age, city): print(f"Name: {name}, Age: {age}, City: {city}") print_info("Alice", 30, "New York")

Call by specifying parameter names (order does not matter)

print_info(age=30, city="New York", name="Alice")

Note on mixed usage: Positional arguments must come before keyword arguments.

12/35

13 of 35

3. Global variables and local variables

5.1 Functions

global variables

Defined outside the function, accessible from all areas

global keyword

Required when modifying global variables within a function

local variables

Defined inside a function, destroyed after the function ends

x = 10 # global variable

def foo():

global x

x = 20

print(x)

foo() # output: 20

print(x) # output: 20

If a global variable with the same name exists, the local variable takes precedence.

13/35

14 of 35

5.2 Class

15 of 35

1. Class basic concept

5.2 Class

Object ( instance )

Actual created as a class object

Method

Defines the behavior of the instance function

attribute

Instance state/ data save

class

Template for creating objects

15/35

16 of 35

2. Class Definition and Use

5.2 Class

Class definition

class Dog: def __init__(self, name, breed): self.name = name self.breed = breed def bark(self): print(f"{self.name} says woof!")

Create an instance

my_dog = Dog("Buddy", "Golden Retriever")

Property access and methods Call

print(my_dog.name) # Output: Buddy print(my_dog.breed) # Output: Golden Retriever my_dog.bark() # Output: Buddy says woof!

Main point

- Initialize instances with constructor `__init__`

- Executing object actions through method calls

1

2

3

4

16/35

17 of 35

3. Inheritance

5.2 Class

Parent class definition

Includes basic properties and methods

child class definition

Inheriting and extending parent classes

Method Overriding

Concrete in child class avatar

class Animal: def __init__(self, name): self.name = name def speak(self): pass # Implemented in child class class Dog(Animal): def speak(self): print(f"{self.name} says woof!") class Cat(Animal): def speak(self): print(f"{self.name} says meow!") my_dog = Dog("Buddy") my_cat = Cat("Whiskers") my_dog.speak() # Output: Buddy says woof! my_cat.speak() # Output: Whiskers says meow!

17/35

18 of 35

4. super() function

5.2 Class

super() function role

Example cord

Execution results​

  • Extend functionality by calling parent class methods from child classes
  • duplication in inheritance structures Minimize

class Parent: def __init__(self, name): self.name = name def greet(self): print(f"Hello, my name is {self.name}") class Child(Parent): def __init__(self, name, age): super().__init__(name) self.age = age def greet(self): super().greet() print(f"I am {self.age} years old") child = Child("Alice", 12) child.greet()

  • Hello, my name is Alice
  • I am 12 years old

18/35

19 of 35

5.3 type Hints and �function Documentation

20 of 35

1. Type hints

5.3 type Hints and function Documentation

1

concept

Increase readability by specifying parameters and return types of variables and functions.

2

characteristic

It does not affect code execution, but is used by static analysis tools to detect errors.

x: int = 10 y: str = "Hello" def add(a: int, b: int) -> int: return a + b

20/35

21 of 35

2. Docstring

5.3 type Hints and function Documentation

def greet_person(person: str, age: int) -> str: """ A function that returns a greeting to the given person. :param person: The name of the person to greet (string) :param age: The person's age (integer) :return: A string containing the greeting """ return f"Hello, {person}! You are {age} years old."

1

concept

Functions , classes , and modules Features and Usage Explaining string

2

How to write

with three quotes Wrapped write

21/35

22 of 35

5.4 Module

23 of 35

1. Module generation

5.4 Module

What is a module?

  • A unit of code that groups related functions, classes, and variables into a single file.
  • Code reuse and maintainability exaltation

Create a module Example :

File name: mymodule.py

def greet(name): return f"Hello, {name}!" def add(a, b): return a + b

23/35

24 of 35

2. Module Usage & 3. Installation Path

5.4 Module

1

module How to use :

  • Import the entire module: import mymodule
  • Importing a specific function/class: from mymodule import greet
  • Using an alias: from mymodule import greet as gr

2

Installing the module Path :

  • root directory, .frozen, /lib

3

installation Steps :

  1. Saving files and creating directories in Thonny
  1. Save the module (mymodule.py) and the main program (main.py) separately
  1. Check the list of files on the device and run it

24/35

25 of 35

4. MicroPython On the device module Install (1)

5.4 Module

  • Thonny Run
  • ❶ Click the [View] tab, then �❷ click [File] to display a list of files on the left.
  • Click the ❸ [hamburger (≡)] button next to the MicroPython device
  • ❹ Click [New Directory].

file inventory mark

Directory making

25/35

26 of 35

4. MicroPython On the device module Install (2)

5.4 Module

❺ Specify the name of the directory to be created �❻ Click the [Confirm] button.

The directory created on the left Appearance

Directory Specify

Directory Created

26/35

27 of 35

4. MicroPython On the device module Install (3)

5.4 Module

❼ Click the [File] tab, then ❽ click [Save as].

Select the storage device as ❾ [MicroPython device].

file Save

device Select

27/35

28 of 35

4. MicroPython On the device module Install (4)

5.4 Module

❿ Select the directory you created.

Name the file (11) mymodule.py and click the (12) [OK] button.

Directory Select

file name Specify

28/35

29 of 35

4. MicroPython On the device module Install (5)

5.4 Module

1

Installed modules

As you can see in [Figure 5-10], the module was successfully installed.

2

module check

You will see the mymodule.py file inside the directory you created in your file browser .

29/35

30 of 35

5. MicroPython On the device Main program Install (1)

5.4 Module

is installed by default There is

❶ Click the [File] tab, then ❷ click [Save as].

By default Installed program

new By name Save

30/35

31 of 35

5. MicroPython On the device Main program Install (2)

5.4 Module

❸ Select [MicroPython Device].

Name the file ❹ main.py and click the ❺ [OK] button.

save device Select

file name Specify

31/35

32 of 35

5. MicroPython On the device Main program Install (3)

5.4 Module

File name check

The file name of the input window that was active has been changed to main.py.

execution method

If you click the [Run] button in this state, main.py will be executed .

automatic execution

When the MicroPython device boots, main.py is automatically executed .

As shown in [Figure 5-15], the main program is installed and ready to run.

32/35

33 of 35

Practice Problems (1/2)

1

In MicroPython The function To use When Advantages and limitations Please explain .

In MicroPython class Make it What you can get when you use it The advantage of the program is The structure' From the perspective Please explain .

2

33/35

34 of 35

Practice Problems (2/2)

3

next As a condition Class and its class Using The program Make it .

[ Condition 1] Class making

  • class Name : SayDays
  • Object When making , pass it on Parameters : year, month, day
  • Entered year​ As a standard Need to find leap years (years with 29 days in February )
  • Method days( ): As of January 1 of the current year Which one It's a day Let me know
  • Method days_left ( ) : As of December 31 of the current year remainder Number of days Let me know
  • Method weekday( ) : By numbers Day of the week Let me know (0: Saturday )
  • Method weekday_name ( ) : Day of the week In Korean Let me know (0: Saturday )
  • day of the week The calculation is Zeller calculation method Follow
  • import statement Do not use

[ Condition 2] In front made class Use it Next together program making

  • S ayDays Object generation
  • while True :
  • i nput statement Any date Input received
  • Print days( ), days_left ( ), week( ), week_name ( )

34/35

35 of 35

Q&A

Copyright© 2025 Hanbit Academy, Inc.

All rights reserved.