Python/기초

파이썬 기초⑦ 클래스

망고고래 2024. 6. 20. 20:49

1. 클래스 선언과 사용

1) 클래스 선언: class

class MYClass:
	MyVar = 0

 

2) 인스턴스 생성

인스턴스명 = 클래스명()
MyInstance = MyClass()

 

3) 인스턴스 내의 변수 사용

MyInstance.MyVar
0

 

 

2. 클래스 내장 요소

1) 클래스 내장 속성 보기: dir(클래스명)

print(dir(MyInstance))

 

['MyVar', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']

 

2) 상세 설명: help('내장 속성')

help('__class__')

 

3. 생성자

class MyClass:
    Greeting = ""
    # 인스턴스가 생성될 때 호출, 매개변수 Name의 기본값 there
    def __init__(self, Name="there"):
    	# Greeting에 값 대입
        self.Greeting = Name + "!"
    def SayHello(self):
        print("Hello {0}".format(self.Greeting))

MyInstance = MyClass()
MyInstance.SayHello()
Hello there!

(위에서 이어서)

# __init__에 Amy 전달
MyInstance2 = MyClass("Amy")
MyInstance2.SayHello()

# MyInstance의 Greeting을 Harry!로 변경
MyInstance.Greeting = "Harry!"
MyInstance.SayHello()
Hello Amy!
Hello Harry!

 

 

4. 변수

1)클래스 변수

인스턴스 생성 없이 클래스명으로 접근

class MyClass:
    Greeting = ""
    def SayHello(self):
        print("Hello {0}".format(self.Greeting))

MyClass.Greeting = "Zelda"
MyClass.Greeting
'Zelda'

 

2)인스턴스 변수

1)의 코드에 이어서

MyInstance = MyClass()
MyInstance.SayHello()
Hello Zelda

 

class MyClass:
    def DoAdd(self, Value1=0, Value2=0):
        Sum = Value1 + Value2
        print("The sum of {0} plus {1} is {2}.".format(Value1, Value2, Sum))

MyInstance = MyClass()
MyInstance.DoAdd(1, 4)

인스턴스 변수 Value1, Value2, Sum을 가진다.

 

 

 

 

5. 함수

1)클래스 함수

인스턴스 생성 없이 사용 가능, 클래스명으로 접근

class MyClass:
    def SayHello():
        print("Hello there!")

MyClass.SayHello()
Hello there!

 

2)인스턴스 함수

인스턴스 생성, 인스턴스명으로 접근

class MyClass:
    def SayHello(self):
        print("Hello there!")

MyInstance = MyClass()
MyInstance.SayHello()
Hello there!

 

 

3)특수한 매개변수

(1)*args(Non-keyword Arguments)

  • 임의 개수의 positional 인수를 받을 수 있음
  • 함수 정의 시 args 앞에 *를 붙여 사용
  • *args는 튜플 형태로 함수에 전달, 함수 내에서 일반 튜플처럼 다룰 수 있음
def print_numbers(*args):
    for arg in args:
        print(arg)

print_numbers(1, 2, 3)  # 출력: 1 2 3
print_numbers(4, 5, 6, 7, 8)  # 출력: 4 5 6 7 8

(2)**kwargs(Keyword Arguments)

  • 임의 개수의 keyword 인수를 받을 수 있음
  • 함수 정의 시 kwargs 앞에 **를 붙임
  • 딕셔너리 형태로 함수에 전달, 함수 내부에서 일반 딕셔너리처럼 다룰 수 있음
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Alice", age=25, city="Seoul")
# 출력:
# name: Alice
# age: 25
# city: Seoul

 

 

 

6. 상속

class 클래스명(상속할 클래스명)

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def introduce(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

class Student(Person):
    def __init__(self, name, age, grade):
        super().__init__(name, age)
        self.grade = grade
    
    def study(self):
        print(f"{self.name} is studying hard to get good grades.")

# 객체 생성
person = Person("John", 35)
person.introduce()  # 출력: Hello, my name is John and I am 35 years old.

student = Student("Jane", 18, 10)
student.introduce()  # 출력: Hello, my name is Jane and I am 18 years old.
student.study()      # 출력: Jane is studying hard to get good grades.

 

 

Animal 클래스를 상속하는 Chicken 클래스

class Animal:
    def __init__(self, Name="", Age = 0, Type=""):
        self.Name = Name
        self.Age = Age
        self.Type = Type
    def GetName(self):
        return self.Name
    def SetName(self, Name):
        self.Name = Name
    def GetAge(self):
        return self.Age
    def SetAge(self, Age):
        self.Age = Age
    def GetType(self):
        return self.Type
    def SetType(self, Type):
        self.Type = Type
    def __str__(self):
        return "{0} is a {1} aged {2}".format(self.Name, self.Type, self.Age)

class Chicken(Animal):
    def __init__(self, Name="", Age=0):
        self.Name = Name
        self.Age = Age
        self.Type = "Chicken"
    def SetType(self, Type):
        print("Sorry, {0} will always be a {1}".format(self.Name, self.Type))
    def MakeSound(self):
        print("{0} says Cluck, Cluck, Cluck!".format(self.Name))

 

 

'Python > 기초' 카테고리의 다른 글

파이썬 기초⑥ 컬렉션  (0) 2024.06.19
파이썬 기초⑤ 리스트 다루기  (0) 2024.06.18
파이썬 기초④ 문자열 다루기  (0) 2024.06.17
파이썬 기초③  (0) 2024.06.13
파이썬 기초②  (0) 2024.06.13