4-5. Descriptor(2)

uoayopยท2021๋…„ 3์›” 27์ผ
0

Leaf์™€ Python

๋ชฉ๋ก ๋ณด๊ธฐ
19/21
post-thumbnail

์–ด๋ ค์šด ๊ฒƒ๋“ค์€ ๊ฑฐ์˜ ๋ฐฐ์šด ๊ฒƒ ๊ฐ™์œผ๋‹ˆ ์ „์ฒด์ ์ธ ๋ณต์Šต์„ ํ•˜๋Š” ๋งˆ์Œ์œผ๋กœ ๊ฐ€๋ณ๊ฒŒ ๋“ค์—ˆ๋‹ค.

Descriptor

  • Descriptor vs property
  • Low level vs high level
  • descriptor ์˜ˆ์ œ ์‹ฌํ™”

Descriptor vs Property

descriptor

low level์—์„œ __get__,__set__ ์œผ๋กœ ์˜ˆ์•ฝ์ด ๋˜์–ด์žˆ๋Š” ์‹œ์ ์— ์šฐ๋ฆฌ๊ฐ€ ์›ํ•˜๋Š” ์ž‘์—…์„ ์ถ”๊ฐ€ํ•  ์ˆ˜ ์žˆ๋‹ค.

  1. ์ƒํ™ฉ์— ๋งž๋Š” ๋ฉ”์†Œ๋“œ ๊ตฌํ˜„์„ ํ†ตํ•œ ๊ฐ์ฒด ์ง€ํ–ฅ ํ”„๋กœ๊ทธ๋ž˜๋ฐ ๊ตฌํ˜„์ด ๊ฐ€๋Šฅํ•˜๋‹ค.
  2. Property์™€ ๋‹ฌ๋ฆฌ ์žฌ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•˜๋‹ค. ( ; ๋‹ค๋ฅธ ๊ฐ์ฒด์˜ ์†์„ฑ๊ฐ’์œผ๋กœ )
  3. ORM framework์—๋„ ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•˜๋‹ค.

property

๋น„๊ต์  high level์—์„œ ๋™์ž‘ํ•˜๋ฉฐ, annotation์„ ๋‹ฌ์•„์„œ ๋ณธ์—ฐ์˜ getter,setter ์—ญํ• ์„ ํ•  ์ˆ˜์žˆ๊ฒŒ ํ•ด์ค€๋‹ค.


์‹ค์Šต ์˜ˆ์ œ

ํ˜„์žฌ directory์˜ ํด๋”, ํŒŒ์ผ์˜ ๊ฐœ์ˆ˜๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“ค์–ด๋ณด์ž

  • ํŒŒ์ผ์˜ ๊ฐœ์ˆ˜๋ฅผ ์„ธ๋Š” ํด๋ž˜์Šค๋Š” ํŒŒ์ผ์„ ์ฝ๊ธฐ๋งŒ ํ•˜๋ฉด ๋˜๋‹ˆ๊นŒ non-data descriptor ์ด๋‹ค.
import logging
import os
class DirectoryFileCount:
    def __get__(self, obj, objtype=None):
        return len(os.listdir(obj.dirname))

# DirectoryPath๋กœ ๊ฒฝ๋กœ๋ฅผ ๋ฐ›์•„์„œ directoryFileCount๊ฐ€ ๊ฐœ์ˆ˜๋ฅผ ๋ฐ˜ํ™˜ํ•  ๊ฒƒ์ด๋‹ค.

class DirectoryPath:
    # descriptor instance
    size = DirectoryFileCount()

    def __init__(self, dirname):
        self.dirname = dirname

โญ๏ธ DirectoryPath๊ฐ€ size๋ผ๋Š” ์†์„ฑ์œผ๋กœ DirectoryFileCount๋ฅผ Descriptor๋กœ ๊ฐ–๋Š”๋‹ค๊ณ  ์ƒ๊ฐํ•˜๋ฉด ๋œ๋‹ค!

# ํ˜„์žฌ ๊ฒฝ๋กœ
s = DirectoryPath('./')
print(s.size)

# ---------------ํ—ท๊ฐˆ๋ฆด ๋•Œ ์ถœ๋ ฅ ์šฉ๋„
print('ex 1>', dir(DirectoryPath))
#  [... , 'size']

print('ex 1>', DirectoryPath.__dict__)
#  'size': <__main__.DirectoryFileCount object at 0x7f8de31c8fa0>,
# size ๋ณ€์ˆ˜์— directoryFileCount ๋ฉ”์†Œ๋“œ๊ฐ€ ์ฐธ์กฐ๋˜์–ด ์žˆ๋‹ค~

print('ex 1>', dir(s))
#  [... , 'size']

print('ex 1>', s.__dict__)
# ex 1> {'dirname': './'}

[์ถœ์ฒ˜]

์ธํ”„๋Ÿฐ - ๋ชจ๋‘๋ฅผ ์œ„ํ•œ ํŒŒ์ด์ฌ : ํ•„์ˆ˜ ๋ฌธ๋ฒ• ๋ฐฐ์šฐ๊ธฐ Feat. ์˜คํ”ˆ์†Œ์Šค ํŒจํ‚ค์ง€ ๋ฐฐํฌ (Inflearn Original)

profile
slow and steady wins the race ๐Ÿข

0๊ฐœ์˜ ๋Œ“๊ธ€