[Python] 객체와 라이브러리

2023. 4. 11. 16:38Language/Python

- 객체와 클래스

클래스(class) > 객체(object)

클래스 안에 여러개의 객체가 들어가있다

클래스 안에 있는 객체를 호출하여 사용한다 (미리 만들어둔 부품을 가져와 새로운 것을 만든다)

   - attribute : 클래스 안에 있는 객체의 변수

   - method : 클래스 안에 있는 객체의 함수

 

사용법

class이름.method이름(인자)

 

class 문법

class 클래스이름:
    attribute 선언
    method 선언

 

class Quad: - 클래스의 이름 첫 글자는 대문자로 한다
    height = 0
    width = 0
    color = ''
    
    def get_area(self): - 메소드의 이름 첫 글자는 소문자로 한다
        return self.height * self.width

 

quad1 = Quad()
quad1.height = 4
quad1.width = 3
quad1.color = 'red'
quad1.get_area()

12

 

라이브러리

math 라이브러리

import math
num = int(math.pow(3, 3))
print (num)

27

math.factorial(7)

5040

 

math 라이브러리에 있는 함수 중, sqrt, factorial 함수만 import
from math import sqrt, factorial

num = sqrt(5)
num2 = factorial(5)

print (num2)

120

 

다음과 같이 쓰면, 해당 라이브러리에 있는 모든 함수를 라이브러리명 없이 쓸 수 있음

math 라이브러리에 있는 모든 함수를 import
from math import *
num = sqrt(5) + factorial(3) 
print (num)

8.23606797749979

 

라이브러리에 있는 함수명이 길거나 해서 다른 이름으로 쓰고 싶으면 다음과 같이 작성

import math as d
num = d.factorial(5)
print (num)

120

 

factorial() 함수를 f()로 사용 가능
from math import factorial as f
num = f(5)
print (num)

120

 

반응형