본문 바로가기

프로그램언어/Python

파이썬 코딩스타일

반응형

Class

_ convention

class Price:
    def __init__(self, price):
        self._price = price

    def _double_price(self):
        return self._price * self_hidden_factor

    def get_double_price(self):
        return self._double_price()
  • 모듈 내에서만 사용하는 private 클래스/함수/변수/메서드를 선언할 때 _ 으로 시작한다.
  • from module import * 으로 임포트할 때 이 컨벤션으로 시작한 것들은 무시가 된다. 다만, weak internal use indicator 라고 부르며 직접 가져다가 쓰는것은 가능한 정도로 완전한 private 을 강조할 수는 없다.

self

a = FourCal()
a.setdata(4, 2)
// def setdata(self, first, second):
  • a -> self
  • '4' -> 'first'
  • '2' -> 'second'
FourCal.setdata(a, 4, 2)
  • 클래스를 통해 매서드를 호출할 수 있다.

constructor

class FourCal:
    def __init__(self, first, second):
        self.first = first
        self.second = second
a = FourCal(4, 2)
  • __init__ 는 생성자, 객체가 생성될때 자동으로 호출되는 메서드

inheritance

class MoreFourCal(FourCal):
    def pow(self):
        result = self.first ** self.second
        return result
  • 상속은 기존 클래스를 변경하지 않고 기능을 추가하거나 기존 기능을 변경하려고 할 떄 사용한다.

method override

class SafeFourCal(FourCal):
    def div(self):
        if self.second == 0:
            return 0
        else:
            return self.first / self.second

class variable

class Family:
    lastname = "김"
print(Family.lastname)
// 김

a = Family()
b = Family()
print(a.lastname)
print(b.lastname)
// 김
// 김

Family.lastname = '박'
print(a.lastname)
print(b.lastname)
//박
//박
  • 클래스 변수를 변경하면 모든 인스턴스의 클래스 변수가 변동된다
a.lastname = '최'
print(a.lastname)
// 최
print(Family.lastname)
// 박
  • 클래스 변수와 같은 객체변수가 생성될 수 있다.
  • 클래스 변수에 영향을 주지는 않는다.

for _

for _ in range(10)
ret = [0 for _ in range(10)]

if

if ret == 2:
    return 0

zip, 3 항 연산자

for num, word in zip(numbers, up_down):
    if word == "UP":
        left = left if num < left else num + 1

global variable

result1 = 0

def add1(num):
    global result1
    result += num
    return result1

type

a = FourCal()
type(a)
// <class '__main__.FourCal'>
반응형