class in 파이썬 & loop

Bor·2021년 11월 13일
0
post-thumbnail

파이썬의 객체

놀랍게도 파이썬도 객체지향형 프로그래밍 언어! 야너두? 객체는 클래스로 생성되며 이러한 객체는 특정한 값들을 저장하는 attribute들과 기능을 수행하는 method들로 구성되어 있다. 클래스로 객체를 생성하기 때문에 클래스에 정의한 이러한 attribute와 method는 그래도 객체에 존재하게 된다. 이러한 클래스의 attribute를 멤버변수, 메소드를 멤버함수라고도 한다.

클래스로 객체 만들기

다음 예제에는 1개의 attribute와 2개의 method를 가지고 있는 클래스 You가 있다. 먼저 main 부분에서 You를 이용해 객체 my를 만든다. 그러면 클래스 You에 정의된 내용 그대로 객체로 생성되며, 그 어트리뷰트와 메소드들은 my가 사용하게 되는 것이다.

#클래스 선언
class You:
    name = '' #attribute 정의
    
    def setname(self, username): 
        self.name = username
        # this.name = username 이런 느낌인가
        
    def show(self):
        print('이름:', self.name)

#main
my = You()
my.setname('보람')
my.show()

그러나 파이썬은 항상 멤버변수 앞에 self. 을 붙이기 때문에 
위와 같이 별도로 멤버변수의 속성을 정의할 필요가 없다.

class You:
    def setname(self, username):
        self.name = username
    def show(self):
        print('이름:', self.name)

생성자

멤버변수에 값을 입력하기 위해 위에서는 별도로 메소드를 정의했다. 그런데 객체지향형 클래스에는 기본적으로 멤버변수를 초기화 하는 메소드가 따로 있다. 이것을 생성자라고 하며 생성자는 객체를 생성하면 자동으로 실행된다. 이것이 가능하려면 클래스로 객체를 생성 시에 초기화할 값들을 입력해주어야 할 것이다. '보람'과 26의 값을 n과 a에 저장하여 이를 이용하여 멤버 변수들에게 값을 할당하게 된다.

class You:
    def __init__(self, n, a):
        self.name = n
        self.age = a
    
    def show(self):
        print('이름:', self.name, '나이:', self.age)
        
my = You('보람',26) #객체가 생성될 때 자동으로 __inint__실행
my.show()
Q 6.3
class Calc:
    def __init__(self,n1,n2):
        self.a = n1
        self.b = n2
        
    def calculate(self, op): 
        if op == '+':
            print(self.a, op, self.b,'=', self.a+self.b)
         
        if op == '*':
            print(self.a, op, self.b,'=', self.a*self.b)    
            
#test 
num1 = int(input('첫번째 수: '))
num2 = int(input('두번째 수: '))
객체 = Calc(num1, num2)
객체.calculate('*')
객체.calculate('+')

❌ 객체.calculate를 해야함. Calc 생성자에 직접 걸면 에러가 난다! ❌
Calc.calculate를 하는 순간 op를 입력해줘도 아래와 같은 에러가 난다. 
calculate() missing 1 required positional argument: 'op' 

다양하고 편리한 기능들

반복문

array = [[9,9], [0,4], [2,3]]
for x,y in array: 
    print(x , y)
    
Q 6.5
array = [['도윤', 21], ['b', 26], ['c',34]]
for x,y in array:
    print(x, ':', y, '세')

빈도수

Q 6.6
text = "어서 오세요! 어서 오세요! 오래 기다렸다구요."
def max_counts(text):
    skips = ['!',  "'", "."]
    
    for skip in skips:
        text = text.replace(skip, '')
    
    print(text.split(' ')) #['어서', '오세요', '어서', '오세요', '오래', '기다렸다구요']
    
    counts = {} 
    
    for ch in text.split(' '):
        if ch in counts:
            counts[ch] += 1
            # print(counts)
        else:
            counts[ch] = 1  
            # print(counts)
    print(counts) #여기 교재 오류임 

    
       
max_counts(text)  
people = ['침', '침', '펄','옥', '펄','침']

def max_count(people):
    counts = {}
    for i in people:
        if i in people:
            counts[i] +=1
        else:
            counts[i] = 1
        return counts

counts = max_count(people)

first = []
max_num = max(counts.values())
for x, y in counts.items():
    print(x, y)
    if y == max_num:
        first.append(x)
print('1등', first)    
            

이번 학기 수강하는 과목의 점수를 입력 받아 리스트에 저장, 합격 불합격 과목의 수를 각각 출력

score  = []
p = 0
f = 0

n = int(input('이번학기 수강 과목 수: '))

for i in range(n):
    #i -> 0부터 n-1 
    score_elem = int(input('과목 점수: '))
    print('score {} : {}'.format(i+1,score_elem))
    score.append(score_elem)
    
for i in range(n):
    if score[i] >= 80:
        p += 1
    else:
        f += 1
print('pass: {}'.format(p))
print('fail: {}'.format(f))

사용자로부터 시작과 끝값을 입력 받은 후 3의 배수 제외한 모든 숫자의 합

start = int(input('시작값: '))
end = int(input('끝값: '))
sum = 0
for i in range(start, end+1):
    if i % 3 != 0:
        sum += i
        
print(sum)

11/13 : 데이터형 객체에 대해서도 이후에 추가적으로 공부할 것!

0개의 댓글