객체

주연·2021년 9월 14일
0

Python

목록 보기
2/3

객체 용어 정리

클래스 Class: 하나의 형식, 템플릿
메소드 Method: 클래스 내 정의된 기능, 함수(행동)
필드, 속성 Field or attribute: 클래스 내 데이터(특징)
객체, 인스턴스 Object or Instance: 클래스의 정의대로 만들어진 객체

class Animal:
	x = 0
    	
        def num(self):
        	self.x = self.x + 1
            	print("num: ", self.x)
                
abc = Animal()

abc.num() #Animal.num(abc)와 같다
abc.num()

> num: 1
num: 2

Animal이라는 클래스안에 num이라는 메서드 존재,

abc = Animal(): Animal 객체를 생성해서 abc변수에 저장
abc.num(): 객체에게 num()실행하라고 알려줌.

dir(), type()

dir()은 객체가 수행할 수 있는 작업들을 알려준다.
1)

class Animal:
	x = 0
    	
        def num(self):
        	self.x = self.x + 1
            	print("num: ", self.x)
                
abc = Animal()

print("type ", type(abc))
print("dir ", dir(abc))

>type <class '__main__.Animal'>
dir ['__class__', .. , 'num', 'x']

2)

x = 'hello'
dir(x)

>['__add__', '__class__', ...., '__str__',
'find', 'index', 'split', ..., 'lower']

여기서 __ 표시되어 있는 것들은 파이썬이 자체적으로 사용하는 것으로 무시해도 된다.

생성자, 소멸자

생성자: 객체가 생성될 때 불러오는 문장

class Animal:
	x = 0
    	
        def __init__(self) : #생성자
        	print('constructed')
            
        def num(self):
        	self.x = self.x + 1
            	print("num: ", self.x)
                
                def __del__(self) : #소멸자
        	print('destructed')
            
abc = Animal()
abc.num()
abc.num()
abc = 42 #객체 소멸됨
print(abc)

>constructed
num: 1
num: 2
destructed
42
  • 다수의 객체를 만들 수 있다. 동일 클래스의 다중 인스턴스를 가질 수 있다.)
  • 각각의 인스턴스는 자신만의 인스턴스 변수를 갖고 있다.
class Animal:
	x = 0
    name = ""
    	
        def __init__(self,z) :
        	self.name = z
        	print(self.name, 'constructed')
            
        def num(self):
        	self.x = self.x + 1
            	print(self.name, "num: ", self.x)
            
abc = Animal("Kim")
def = Animal("Park")

abc.num()
def.num()
abc.num()

>Kim constructed
Park constructed
Kim num: 1
Park num: 1
Kim num: 2

상속

자식 클래스는 부모 클래스의 모든 기능을 상속받는다 + 자신의 기능을 갖고 있다.
여러번 재사용 가능하다.

class Animal:
	x = 0
    name = ""
    	
        def __init__(self,z) :
        	self.name = z
        	print(self.name, 'constructed')
            
        def num(self):
        	self.x = self.x + 1
            	print(self.name, "num: ", self.x)
            
class Dog: #자식 클래스
	point = 0
    	
        def bark(self) :
        	self.point = self.point + 7
            self.num()
        	print(self.name, 'point ', self.point)
            
a = Animal("Kim")
a.num()

>Kim constructed
Kim num: 1

d = Dog("Park")
d.num()
d.bark()

>Park constructed
Park num: 1
park num: 2
park point 7
profile
공부 기록

0개의 댓글