2.7 Classes #Writing Idiomatic Python 3.1

oen·2022년 7월 7일
0

1. isinstance 함수 사용해서 객체의 type 알아내기

isinstance(object, type or tuple of types) 은 빌트인 함수로
만약 객체가 두번째 인자와 같은 타입이거나 서브타입이면 True 반환

두번째 인자가 튜플이면: 객체가 튜플의 원소 중 하나라도 같은 타입이거나 서브타입이면 True 반환

isinstance("Hello", (float, int, str, list, dict, tuple))
True

👎

def get_size(some_object):
    '''
    - sequence: size = len(some_object)
    - True, False, None: size = 1
    - integers, floats: size = int(some_object)
    '''
    try:
        return len(some_object)
    except TypeError:
        if some_object in (True, False, type(None)):
            return 1
        else:
            return int(some_object)


print(get_size('hello'))
print(get_size([1, 2, 3]))
print(get_size(10.0))
5
3
10

👍

def get_size(some_object):
    if isinstance(some_object, (list, dict, str, tuple)): # *
        return len(some_object)
    elif isinstance(some_object, (bool, type(None))):
        return 1
    elif isinstance(some_object, (int, float)):
        return int(some_object)


print(get_size('hello'))
print(get_size([1, 2, 3]))
print(get_size(10.0))
5
3
10

2. private 데이터 라는걸 나타내기 위해 함수나 변수 앞에 _ 붙이기

_ : protected
사용자가 직접적으로 사용하면 안된다.
__ : private
서브클래스에서 접근하면 안된다.

👎

class Foo:
    def __init__(self):
        self.id = 8
        self.value = self.get_value()

    def get_value(self):
        pass

    def should_destroy_earth(self):
        return self.id == 42


class Baz(Foo):
    def get_value(self, some_new_parameter):
        pass


class Qux(Foo):
    def __init__(self):
        super().__init__()
        self.id = 42


q = Qux()
print(q.should_destroy_earth())
print(q.id == 42)

b = Baz()
True
True
TypeError: get_value() missing 1 required positional argument: 'some_new_parameter'

👍

from inspect import Attribute


class Foo:
    def __init__(self):
        self.__id = 8
        self.value = self.__get_value()

    def get_value(self):
        pass

    def should_destroy_earth(self):
        return self.__id == 42

    __get_value = get_value


class Baz(Foo):
    def get_value(self, some_new_parameter):
        pass


class Qux(Foo):
    def __init__(self):
        self.id = 42
        super().__init__()


q = Qux()
print(q.should_destroy_earth())
print(q.id == 42)

getattr(q, '__id')

False
True
AttributeError: 'Qux' object has no attribute '__id'

3. property

👎

class Product:
	def __init__(self, name, price):
    	self.name = name

👍

class Product:
	def __init__(self, name, price):
    	self.name = name
    	self._price = price
    
    @property
    def price(self):
    	return self._price * TAX_RATE
        
    @price.setter
    def price(self, value):
    	self._price = value

4. __repr__

👎

class Foo:
    def __init__(self, bar=10, baz=12, cache=None):
        self.bar = bar
        self.baz = baz
        self._cache = cache or {}

    def __str__(self):
        return f'Bar is {self.bar}, Baz is {self.baz}'


def log_to_console(instance):
    print(instance)


log_to_console([Foo(), Foo(cache={'x': 'y'})])
[<__main__.Foo object at 0x1029a2d30>, <__main__.Foo object at 0x1029c36a0>]

👍

class Foo:
    def __init__(self, bar=10, baz=12, cache=None):
        self.bar = bar
        self.baz = baz
        self._cache = cache or {}

    def __str__(self):
        return f'Bar is {self.var}, Baz is {self.baz}'

    def __repr__(self):
        return f'Foo({self.bar}, {self.baz}, {self._cache})'


def log_to_console(instance):
    print(instance)


log_to_console([Foo(), Foo(cache={'x': 'y'})])
[Foo(10, 12, {}), Foo(10, 12, {'x': 'y'})]

5. __str__

👎

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y


p = Point(1, 2)
print(p)
<__main__.Point object at 0x109140d30>

👍

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return f'{self.x}, {self.y}'


p = Point(1, 2)
print(p)
1, 2
profile
🐾

0개의 댓글