Blair  - Soul Eater [파이썬 개념] 클래스, 객체, 속성, 메소드, 인스턴트,생성자

• programming language/python

[파이썬 개념] 클래스, 객체, 속성, 메소드, 인스턴트,생성자

oujin 2022. 7. 19. 10:28
728x90

●절차적 프로그래밍 vs 객체지향 프로그래밍

- 절차적 프로그래밍: 프로그램의 진행이 코드의 순서대로 진행

- 객체지향 프로그래밍: 프로그램의 구성이 객체를 중심으로 진행

        속성(Attribute)메소드(Method)로 구성됩니다. 

        속성: 객체 내부에서 사용되는 변수

        메소드: 객체 내부에서 사용되는 함수

        객체: 그 객체를 정의하고 있는 클래스를 통해 생성됨

 

# 클래스 생성
class Hello:

# 메소드 생성
    def greet(self):
        print('Hello, Python')

# 인스턴스 생성
hi = Hello()

# 메소드 호출
hi.greet()

 

EX)

class  Calculator:
    def set (self, xy) :
        self.one = x
        self.two = y
    
    def add (self, xy) :
        result = self.one + self.two
        return result
    
cal = Calculator()
   
cal.set(15, 20)
print('%d + %d = %d' % (cal.one, cal.two, cal.add(10,20)))
cal.set(11, 22)
print('%d + %d = %d' % (cal.one, cal.two, cal.add(100,200)))

15 + 20 = 35
11 + 22 = 33

 

●생성자(Constructor)

객체를 생성할 때 자동으로 호출되는 함수로써, 객체 생성 시에 객체의 초기화 작업에 사용

__init__()은 반드시 첫번재 인수로 self를 지정해야 한다.

생성자라고 부르는 건 __init__이고 생성자를 통해서 객체가 생성될 때

---> name, age라는 인자를 받아서 name, age라는 변수를   self.name = name self.age = age 이렇게 초기화를 시킴

 

class Member :
    def __init__(self,name ,age ) :
        self.name = name
        self.age = age

    def showMember(self,name ,age ) :
        print('이름 : %s' % self.name)
        print('나이 : %d' % self.age)
        
mem1 = Member('김철수',24 )
mem1.showMember('미미',50)
mem2 = Member('신짱구', 5)
mem2.showMember('신짱구', 5)

이름 : 김철수
나이 : 24
이름 : 신짱구
나이 : 5

 

●속성

  1. 클래스 속성(Class Attribute) : 메소드들의 외부에 정의되어 해당 객체로부터 생성 되는 모든 객체에서 접근 가능
  2. 인스턴스 속성(Instance Attribute) :  메소드 내부에 정의되어 해당 객체에서만 접근 가능한 속성입니다.

 

1. 클래스 속성 ex) 클래스명.속성명

class MyClass :
    number = 100
    
    def inc_10(self): 
        MyClass.number += 10
    
    def inc_20(self): 
        MyClass.number += 20
        
obj1 = MyClass() 
obj1.inc_10()         
print(obj1.number)
  
obj2 = MyClass() 
obj2.inc_20()         
print(obj2.number)

110
130

 

2. 인스턴트 속성 ex) self.속성명

class MyClass :
    def __init__(self, number) :
        self.number = number
        
    def inc_10(self): 
        self.number += 10
    
    def inc_20(self): 
        self.number += 20
        
obj1 = MyClass(100) 
obj1.inc_10()         
obj1.inc_20()
print(obj1.number)
  
obj2 = MyClass(200) 
obj2.inc_10()     
obj2.inc_20() 
print(obj2.number)

110
230

 

●클래스의 상속(부모 → 자식)

객체 지향 프로그래밍에서 자식 클래스는 부모 클래스의 속성과 메소드를 그대로 상속받아 사용할 수 있습니다.

 

class Animal :
    def __init__(self, name):
        self.name = name

    def printName(self):
        print(self.name)
        
class Cat(Animal):
    def __init__(self, name, sound):
        super().__init__(name)
        self.sound = sound
        
    def getname(self):
        print(f'저는 고양이 {self.name}입니다.')
        
    def printSound(self):
        print(self.sound)

cat1 = Cat('꾸꾸','냥냥')
cat1.printName()
cat1.getname()
cat1.printSound()

꾸꾸
저는 고양이 꾸꾸입니다.
냥냥

 

●클래스의 상속(자식부모 )

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def printInfo(self):
        print('이름:%s, 나이:%d' % (self.name, self.age))
        
    def getInfo(self) :
        return self.name + '+ ' + str(self.age)
        
class Student(Person):
    def __init__(self, name, age, department, id):
        super().__init__(name,age )
        self.department = department
        self.id = id 
        
    def printStudentInfo(self):
        name_age = super().getInfo()
        print(name_age)
        print('%s님의 학과:%s, 학번:%s' % (self.name, self.department, self.id))

x = Student('오꾸꾸', 11, '고양이사료학과', '202213798')

x.printInfo()
print("")
x.printStudentInfo()
print("")
x.getInfo()
print(a)

이름:오꾸꾸, 나이:11

오꾸꾸+ 11
오꾸꾸님의 학과:고양이사료학과, 학번:202213798

오꾸꾸+ 11

 

 

 

 

 

 

 

출처: 예제 중심 파이썬 입문

궁금한 부분이 있으면 댓글 부탁드립니다^^

728x90