본문 바로가기
Study (Data Science)/Python

막강한 클래스 (Class)

by 콜라찡 2022. 11. 30.

Everything in Python is an object, and almost everything has attributes and methods.

파이썬(Python)에서 모든 것은 객체(object)다.

그래서 거의 모두가 속성(attributes)  메서드(methods) 를 갖는다.

 

객체(Object) 안에서,

변수(Variable)를 만들면 속성(Attribute; State)이 되고, mycat = 'kola'

함수(Function)를 만들면 메서드가(Method; Behavior) 된다. def genius(self, speed, lr): , mycat

변수는 단지 이름이다. 단지 = 이라는 연산자를 이용해 값을 할당받은 객체를 불러주는 second name이다.


 

  • A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
  • A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

얕은복사란, 

주소를 복사. a=[1,2,3] ; a.append(4) 실행 시, 양 변의 고유 id값(자료존재주소) 가 같아지는 정도. 지금 다른 요소를 추가했어도 a와 리스트의 id가 같은 딱 그정도. 결정적으로 새 객체가 생성되어 새 id가 부여되지는 않음.

깊은복사란,

값을 복사. 원본이 복제되는 느낌. 새로운 객체, 새로운 id를 가짐


Class

개발자가 객체를 직접 설계하기 위해 사용.

Car뒤에 () 를 생략해서 쓰기도 함.

함수 호출과 구분하기 위해 Class명의 첫글자는 꼭 대문자!, 명사를 자주쓰고,

함수는 소문자, blank는 언더바, 동사로 네이밍한다.

자주쓰는 int(10), range(10),dic(x=1,y=2) 도 사실 다 클래스.

.append(a)는 클래스의 메소드임.

 

class Car:
    pass

class Car():
    pass
# Car 클래스입니다.
class Car:
    Class의 State :  Attribute (속성), Variable(변수)로 정의 
    색상: 빨강
    종류: 스포츠 카
  
    color = 'red'
    category = 'sports car'
    ----------------------------------------------------------------
    Class의 Behavior = Method (메소드), Function(함수)로 정의 
    
    def drive(self):                                 # 주행 메소드
        print("I'm driving")
				
    def accel(self, speed_up, current_speed=10):     # 가속 메서드
        '''   
        :param speed_up: 가속
        :param current_speed: 현재 속도
        :type speed_up: string
        :type current_speed: string
        '''
        self.speed_up = speed_up
        self.current_speed = current_speed + speed_up
        print("speed up", self.speed_up, "driving at", self.current_speed)

Class의 State :  Attribute (속성), Variable(변수)로 정의 (차는 빨간색, 스포츠카다)

Class의 Behavior = Method (메소드), Function(함수)로 정의  (주행과 가속이라는 행동을 한다.)

 

1. Coding

  • Method : 첫번째 인자로 (self)를 무조건 갖고, 그 뒤로 인자를 가질지는 메소드마다 다르다.
  • 위에서 drive 메소드는 self 외 인자를 가지지 않았다. 왜냐하면 케바케로 다른 연산을 할 필요가 없고, 단순 I'm driving이라는 문구를 동일하게 출력하면 끝이기 때문이다. 
  • 하지만 accel이라는 Method, 두 개의 또다른 인자를 가진다. 그리고 그 두 인자는 self.인자이름 = 내용을 담고 있다. self.current_speed = current_speend + speed_up 만 정의될 것 같지만, speed_up이라는 인자를 정의해주지 않았기때문에 그 윗줄에 self.speed_up=(just) speed_up이라고 자기 자신을 다시 한 번 정의해준다.
  • 같은 class 안에서 서로 다른 method가 쓰일 때에는 self. 라고 앞에 꼭 붙여줘야한다. class 안에서는 self.method()
class Person:
    def greeting(self):
        print('Hello')
 
    def hello(self):
        self.greeting()    # self.메서드() 형식으로 클래스 안의 메서드를 호출
 
james = Person()
james.hello()    # Hello

2. Calling

mycar = Car()         # 인스턴트화 : 이제 클래스를 쓰겠다는 뜻.

print(mycar.color)    # Attribute 부르기 
mycar.price           # Error. 클래스에 없는 Attribute.

mycar.drive()         # Method 부르기. drive는 인자가 자기자신뿐이라 ()
mycar.accel(5)        # Method. speed_up 인자는 따로 지정할 필요가 없어서 current speed만 지정.

    1. 인스턴스(instanace) : 클래스를 할당받은 변수. mycar. 클래스를부를사람 = 클래스 부르기   내차 = 차클래스

    2. 인스턴스 .(like.of) 찍고 클래스 안에 친구들 부르기    내차의 색상 / 내차의 주행 / 내차의 가속

        (클려스명.속성이나메소드(인스턴스)    차 클래스의 주행에 (내차) 를 넣는것과 같음.  Car.drive(mycar))

 

3. Self

     All of Objects should need the attribution of itself.  

     The Attributes in Class is the attibution of Class. 

     Self is also the attribution of Objects like Attributes and Methods in Class.

class Test2:

   def run1(self, a):
        self.a = float(a) * 10
        print(self.a)

    def run2(self, b):
        b = float(b) + 10
        print(self.b)
        
t.run1(1)  >> 10.0
t.run2(1)  >> AttributeError: 'Test2' object has no attribute 'b'

 

self.a =  이렇게 run1이 가진 a라는 속성을 정해줘야 한다. 데리고 있는 a에게 " 내 성격은!!! "  이렇게 발언권을 한번 줘야 나중에 일을 시켜도 한다는 뜻이다. run2 함수는 데리고있는 b에게 직접 소개할 기회를 주지 않았다. 그래서 b는 성격이 존재하지 않는다고 에러가 나는 것이다.. 다들 성격 확실하군. 하기에러는 self 안줘서 나는 에러!

TypeError: ... takes 0 positional arguments but 1 was given: 메서드의 첫 번째 매개변수를 self로 지정하지 않아서 발생하는 에러입니다. 메서드의 첫 번째 매개변수가 self인지 확인해주세요

 

참고 | 특정 클래스의 인스턴스인지 확인하기

현재 인스턴스가 특정 클래스의 인스턴스인지 확인할 때는 isinstance 함수를 사용합니다. 특정 클래스의 인스턴스가 맞으면 True, 아니면 False를 반환합니다.

isinstance(인스턴스, 클래스)

>>> class Person:
...     pass
...
>>> james = Person()
>>> isinstance(james, Person)
True

isinstance는 주로 객체의 자료형을 판단할 때 사용합니다. 예를 들어 팩토리얼 함수는 1부터 n까지 양의 정수를 차례대로 곱해야 하는데, 실수와 음의 정수는 계산할 수 없습니다. 이런 경우에 isinstance를 사용하여 숫자(객체)가 정수일 때만 계산하도록 만들 수 있습니다.

def factorial(n):
    if not isinstance(n, int) or n < 0:    # n이 정수가 아니거나 음수이면 함수를 끝냄
        return None
    if n == 1:
        return 1
    return n * factorial(n - 1)

 

4. __init__ : 생성자 (Conductor)

객체를 생성할 때 반드시 호출이 되고 제일 먼저 실행되는 특별한 메서드.

즉, __init__(initialize)이라는 이름 그대로 인스턴스(객체)를 초기화.

(스페셜 메서드(special method) ,매직 메서드(magic method) :

앞 뒤로 __(밑줄 두 개)가 붙은 메서드.파이썬이 자동으로 호출해주는 메서드)

class Car:
    color = 'red'                                                             # 클래스 변수
    category = 'sports car'

    def drive(self):
        print("I'm driving")

    def accel(self, speed_up, current_speed=10):
        self.speed_up = speed_up
        self.current_speed = current_speed + self.speed_up
        print("speed up", self.speed_up, "driving at", self.current_speed)
        
class Car2:
    def __init__(self, color, category):       # 초기화 method
        self.color = color
        self.category = category

    def drive(self):
        print("I'm driving")

    def accel(self, speed_up, current_speed=10):
        self.speed_up = speed_up
        self.current_speed = current_speed + self.speed_up
        print("speed up", self.speed_up, "driving at", self.current_speed)
        
        or
   
class Car2:
    def __init__(self, color='red', category='sprots car'):   # 기본값 주기  # 인스턴스변수
        self.color = color
        self.category = category

혹은 

class Car2:
    def __init__(self, color='red', category='sprots car'):        이렇게 기본값으로 지정해도 됨.
        self.color = color
        self.category = category

 

5. 상속 (Inheritance)

기반클래스(Base) -> 파생클래스(Derived)

기반에 없는 함수만 파생에서 만들면 됨.

class Person:
    def greeting(self):
        print('안녕하세요.')
 
class Student(Person):
    def study(self):
        print('공부하기')
 
james = Student()
james.greeting()    # 안녕하세요.: 기반 클래스 Person의 메서드 호출
james.study()       # 공부하기: 파생 클래스 Student에 추가한 study 메서드
class NewCar(Car):                                    # 클래스 상속받기 
    def fly(self):                                    # 메소드 추가하기 (Add)
        print("I'm flying!! This is the new car!!")

    def drive(self):                                  # 메소드 재정의하기 (Overide)
        print("I'm driving and can fly")
  1. 클래스 상속하기 (inheritance) : 기존 있던 Car 클래스를 NewCar이라는 새 클래스에 재사용.효율적
  2. 메서드 추가하기(add)              : 기존 있던 Car 클래스에 없는 메소드를 추가할 때
  3. 메서드 재정의하기(override)    : 기존 있던 Car 클래스에 있는 메소드를 수정할 때
  4. 부모 메서드 호출하기(super())  : base class의 기능을 쓰려면 상속클래스에 super로 부모클래스의 기능을 불러와야 함
class Person():
  def __init__(self):
    print('Person__init__')
    self.hello='안녕하세요'
  
class Student(Person):
  def __init__(self):
    print('Student__init__')
    super().__init__()   # 3. 바로 쓸 수 있게 이렇게 () 까지 붙여 추가해줘야 함.
    self.school='아이펠'

james=Student()			# 1. Student 클래스를 데러와서
james.school
james.hello             # 2. 부모클래스의 메소드를 바로 못씀
728x90

'Study (Data Science) > Python' 카테고리의 다른 글

기본수학, numpy  (3) 2022.12.01
게임 캐릭터 클래스 만들기  (0) 2022.11.30
Unit 31. 재귀호출 (recursive call)  (0) 2022.11.29
Unit 29. 함수의 return  (0) 2022.11.29
참고) zip( ) 함수  (0) 2022.11.29

댓글