###객체지향
class 이름: self.__이름 = 넣을값 |
__ 이것설정이란 |
__이 붙으면 접근제한 기능을 부과한다 프라이빗 필드를 생성한다고 부른다 |
@이름.getter | 멤버를 읽어오는 메서드 | |
@이름.setter | 멤버를 변경하는 메서드 | |
@classmethod | ||
@property |
### def
def create(name, age):
return {"name" : name, "age" : age}
def to_str(person):
return "{0}\t{1}".format(person["name"],person["age"])
members= [
create("홍길동", 20 ),
create("이순신", 45),
create("강감찬", 35)
]
for member in members:
print(to_str(member))
### class
class Person:
pass
member = Person()
if isinstance(member, Person):
print("member는 Person 클래스의 인스턴스입니다.")
### class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
print("{0} 객체가 생성되었습니다. ".format(self.name))
def __del__(self):
print("{0} 객체가 제거되었습니다. ".format(self.name))
member = Person("홍길동", 20)
print("{0}\t{1}".format(member.name, member.age))
print(dir(member))
### class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
print("{0} 객체가 생성되었습니다. ".format(self.name))
def __del__(self):
print("{0} 객체가 제거되었습니다. ".format(self.name))
def to_str(self):
return "{0}\t{1}".format(self.name, self.age)
member = [
Person("홍길동", 20),
Person("이순신", 45),
Person("강감찬", 35)
]
for member in members:
print(member.to_str())
###class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
print("{0} 객체가 생성되었습니다. ".format(self.name))
def __del__(self):
print("{0} 객체가 제거되었습니다. ".format(self.name))
def to_str(self):
return "{0}\t{1}".format(self.name, self.age)
member = [
Person("홍길동", 20),
Person("이순신", 45),
Person("강감찬", 35)
]
members[0].age = -20
for member in members:
print(member.to_str())
###class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
print("{0} 객체가 생성되었습니다. ".format(self.name))
def __del__(self):
print("{0} 객체가 제거되었습니다. ".format(self.name))
def to_str(self):
return "{0}\t{1}".format(self.name, self.age)
member = [
Person("홍길동", 20),
Person("이순신", 45),
Person("강감찬", 35)
]
members[0].age = -20
for member in members:
print(member.to_str())
###class
class Person:
def __init__(self, name, age):
self.__name = name
self.__age = age
print("{0} 객체가 생성되었습니다. ".format(self.name))
def __del__(self):
print("{0} 객체가 제거되었습니다. ".format(self.name))
def to_str(self):
return "{0}\t{1}".format(self.name, self.age)
def get_name(self):
return self.__name
def get_age(self):
return self.__age
def set_age(self, age):
if age<0:
raise TypeError("나이는 0이상의 값만 허용합니다.")
self.__age = age
member = [
Person("홍길동", 20),
Person("이순신", 45),
Person("강감찬", 35)
]
members[0].set_age(-20)
for member in members:
print(member.to_str())
###class
class Person:
def __init__(self, name, age):
self.__name = name
self.__age = age
print("{0} 객체가 생성되었습니다. ".format(self.name))
def __del__(self):
print("{0} 객체가 제거되었습니다. ".format(self.name))
def to_str(self):
return "{0}\t{1}".format(self.name, self.age)
@property
def name(self):
return self.__name
@property
def age(self):
return self.__age
@age.setter
def age(self, age):
if age<0:
raise TypeError("나이는 0이상의 값만 허용합니다.")
self.__age = age
member = [
Person("홍길동", 20),
Person("이순신", 45),
Person("강감찬", 35)
]
members[0].age = 22
for member in members:
print(member.to_str())
## count
class Person:
count = 0
def __init__(self, name, age):
self.__name = name
self.__age = age
Person.count += 1
print("{0} 객체가 생성되었습니다. ".format(self.name))
def __del__(self):
print("{0} 객체가 제거되었습니다. ".format(self.name))
def to_str(self):
return "{0}\t{1}".format(self.name, self.age)
@property
def name(self):
return self.__name
@property
def age(self):
return self.__age
@age.setter
def age(self, age):
if age<0:
raise TypeError("나이는 0이상의 값만 허용합니다.")
self.__age = age
member = [
Person("홍길동", 20),
Person("이순신", 45),
Person("강감찬", 35)
]
print("현재 Person 클래스의 인스턴스는 총 {0} 개입니다.".format(Person.count))
for member in members:
print(member.to_str())
###classmethod
class Person:
count = 0
def __init__(self, name, age):
self.__name = name
self.__age = age
Person.count += 1
print("{0} 객체가 생성되었습니다. ".format(self.name))
def __del__(self):
print("{0} 객체가 제거되었습니다. ".format(self.name))
def to_str(self):
return "{0}\t{1}".format(self.name, self.age)
@property
def name(self):
return self.__name
@property // 변수선언 . 하고 붙혀쓰면됨
def age(self):
return self.__age
@age.setter
def age(self, age):
if age<0:
raise TypeError("나이는 0이상의 값만 허용합니다.")
self.__age = age
@classmethod //부모 객체를 불러옴
def get_info(cls): // cls 부모겍체 이름정함
return "현재 Person 클래스의 인스턴스는 총 {0} 개입니다.".format(cls.count)
member = [
Person("홍길동", 20),
Person("이순신", 45),
Person("강감찬", 35)
]
print("현재 Person 클래스의 인스턴스는 총 {0} 개입니다.".format(Person.count))
print(Person .get_info())
for member in members:
print(member.to_str())
### 비교 하기
class Person:
count = 0
def __init__(self, name, age):
self.__name = name
self.__age = age
Person.count += 1
print("{0} 객체가 생성되었습니다. ".format(self.name))
def __del__(self):
print("{0} 객체가 제거되었습니다. ".format(self.name))
def to_str(self):
return "{0}\t{1}".format(self.name, self.age)
@property
def name(self):
return self.__name
@property // 변수선언 . 하고 붙혀쓰면됨
def age(self):
return self.__age
@age.setter
def age(self, age):
if age<0:
raise TypeError("나이는 0이상의 값만 허용합니다.")
self.__age = age
@classmethod //부모 객체를 불러옴
def get_info(cls): // cls 부모겍체 이름정함
return "현재 Person 클래스의 인스턴스는 총 {0} 개입니다.".format(cls.count)
def __gt__(self, other):
return self.__age > other.__age //self의 __age필드가 other 객체의 __age 필드보다 크면 ture 반환
def __ge__(self, other):
return self.__age >= other.__age // self의 __age 필드가 other 객체의 __age 필드보다 크거나 같으면 ture 반환
def __lt__(self, other):
return self.__age < other.__age // self의 __age 필드가 other 객체의 __age 필드보다 작으면 true 반환
def __le__(self,other):
return self.__age <= other.__age
def __eq__(self, other):
return self.__age == other.__age
def __ne__(self, other):
return self.__age != other.__age
member = [
Person("홍길동", 20),
Person("이순신", 45),
Person("강감찬", 35)
]
cnt = len(members)
i = 0
while True:
print("members[{0}] > members[{1}] => {2}".format(i, i + 1, members[i] > members[i + 1]))
i += 1
if i == cnt -1:
print("members[{0}] > members[{1}] => {2}".format(i, 0, members[i] > members[0]))
break
### __str()__
class Person:
count = 0
def __init__(self, name, age):
self.__name = name
self.__age = age
Person.count += 1
print("{0} 객체가 생성되었습니다. ".format(self.name))
def __del__(self):
print("{0} 객체가 제거되었습니다. ".format(self.name))
def to_str(self):
return "{0}\t{1}".format(self.name, self.age)
@property
def name(self):
return self.__name
@property // 변수선언 . 하고 붙혀쓰면됨
def age(self):
return self.__age
@age.setter
def age(self, age):
if age<0:
raise TypeError("나이는 0이상의 값만 허용합니다.")
self.__age = age
@classmethod //부모 객체를 불러옴
def get_info(cls): // cls 부모겍체 이름정함
return "현재 Person 클래스의 인스턴스는 총 {0} 개입니다.".format(cls.count)
def __gt__(self, other):
return self.__age > other.__age //self의 __age필드가 other 객체의 __age 필드보다 크면 ture 반환
def __ge__(self, other):
return self.__age >= other.__age // self의 __age 필드가 other 객체의 __age 필드보다 크거나 같으면 ture 반환
def __lt__(self, other):
return self.__age < other.__age // self의 __age 필드가 other 객체의 __age 필드보다 작으면 true 반환
def __le__(self,other):
return self.__age <= other.__age
def __eq__(self, other):
return self.__age == other.__age
def __ne__(self, other):
return self.__age != other.__age
def __str__(self):
return "{0}\t{1}".format (self.__name ,self.__age)
member = [
Person("홍길동", 20),
Person("이순신", 45),
Person("강감찬", 35)
]
for member in members:
print(str(member))
### class child
class Parent:
def __init__(self, family_name):
self.__family_name = family_name
print("Parent 클래스의 init() ..")
@property
def family_name(self):
return self.__family_name
class Child(Parent):
def __init__(self, first_name, last_name):
Parent.__init__(self, last_name)
#super().__init__(last_name)
self.__first__name = first_name
print("Child 클래스의 __init__() ..")
@property
def first_name(self):
return self.__first_name
@first_name.setter
def first_name(self, first_name):
self.__first_name = first_name
@property
def name(self):
return "{0} {1}".format(self.family_name, self.first_name)
child = Child("길동", "홍")
print(child.family_name)
print(child.first_name)
print(child.name)
### 오머라이딩
# -*- coding: utf-8 -*-
class Person:
def __init__(self, family_name):
self.__family_name = family_name
print("Parent 클래스의 __init__() ..")
@property
def family_name(self):
return self.__family_name
class Child(Parent):
def __init__(self, first_name, last_name):
Parent.__init__(self, last_name)
# super().__init__(last_name)
self.__first_name = first_name
print("Child 클래스의 __init__()... ")
@property
def first_name(self):
return self.__first_name
@first_name.setter
def first_name(self, first_name):
self.__first_name = first_name
@property
def name(self):
return "{0} {1}".format(self.family_name, self.first_name)
def print_info(self):
Parent.print_info(self)
# super().print_info()
print("Child: {0}".format(self.name))
child = Child("길동", "홍")
child.print_info()
###연습
# -*- coding: utf-8 -*-
# 15-15.py
class Student:
def __init__(self, name, gender, height):
self.__name = name
self.__gender = gender
self.__height = height
@property
def name(self):
return self.__name
@property
def gender(self):
return self.__gender
@property
def height(self):
return self.__height
@height.setter
def height(self, height):
self.__height = height
def __repr__(self):
retrun "{0}(name: {1}, gender: {2}, height: {3})"\
.format(self.__class__.__name__, self.name, self.gender, self.height)
students = [
student("홍길동", "남", 176.5),
student("이순신", "남", 188.5),
student("유관순", "여", 158.4),
student("강감찬", "남", 182.2)
]
for student in students:
print(student)
print ("name으로 오름차순 정렬후====>")
for student in sorted(students, key=lambda x: x.name):
print(student)
print("name으로 내림차순 정렬 후 ===>")
for student in sorted(students, key=lambda x: x.name, reverse= True):
print(student)
'+++++SW 일일 공부+++++ > SW Expert Aademy' 카테고리의 다른 글
트리구조의 모든 집합 구하기 시프트 활용 (0) | 2020.04.09 |
---|---|
stack (0) | 2020.03.26 |
파이썬 문자열에 대하여 (0) | 2020.02.07 |
Python Dict() (0) | 2020.02.02 |
파이썬 set(), 집합 (0) | 2020.02.02 |