본문 바로가기
IT/Python

Python - Class

by 최고영회 2018. 9. 7.
728x90
반응형
SMALL
class Person:
  salary = 0
  def __init__(self, name):
    self.name = name
  def say_hi(self):
    print('Hello, my name is', self.name)
  def say_salary(cls):
    print('My salary is', cls.salary)
    cls.salary += 1

p1 = Person('Younghoi')
p1.say_hi()
Persin.say_salary()

p2 = Person('Kim')
p2.say_hi()
Person.say_salary()

init method 는 예상처럼 객체/인스턴스가 생성될때 호출되는 method이다.

재미있는것은 클래스변수와 객체 변수가 있다는 것이다.

클래스 변수인 salary는 서로 다른 객체 p1과 p2가 서로 공유할 수 있다.

Person.salary 라고 접근하는 클래스 변수는 self.class.salary 로도 접근 가능하다.

객체지향프로그램의 여러 장점 중 가장 먼저 쉽게 떠올릴 수 있는 "상속" 은 어떻게 표현 할까?


class SchoolMember:
    def __init__(self, name, age):
        self.name = name;
        self.age = age;
        print('(Initialized SchoolMember: ', self.name)
    def tell(self):
        print('Name:{}, Aage:{}'.format(self.name, self.age))

class Teacher(SchoolMember):
    def __init__(self, name, age, salary):
        SchoolMember.__init__(self, name, age)
        self.salary = salary
        print('(Initialized Teacher: {}'.format(self.name))

    def tell(self):
        SchoolMember.tell(self)
        print('Salary', self.salary)

class Student(SchoolMember):
    def __init__(self, name, age, marks):
        SchoolMember.__init__(self, name, age)
        self.marks = marks
        print('(Initialized Student: {}'.format(self.name))

    def tell(self):
        SchoolMember.tell(self)
        print('Marks: ', self.marks)

t = Teacher('Mrs. Lee', 40, 30000)
s = Student('Kim', 25, 90)

members = [t, s]
for member in members:
    member.tell()
728x90
반응형
LIST

'IT > Python' 카테고리의 다른 글

Python - Socket(Client) with struct (쉽게 테스트용 Client 만들기)  (0) 2018.09.11
Python - I/O, File I/O, pickle  (0) 2018.09.10
Python - 자료구조  (0) 2018.08.30
Python - 함수  (0) 2018.08.27
Python - 기본문법  (0) 2018.08.27