- A class is like a form or questionnaire.
- An instance is like a form that has been filled out with information.
- Just like many people can fill out the same form with their own unique information,
many instances can be created from a single class.
- Python class names are written in CapitalizedWords notation by convention.
- Attributes created in .__init__() are called instance attributes.
- An instance attribute’s value is specific to a particular instance of the class.
- On the other hand, class attributes are attributes that have the same value for all class instances.
- You can define a class attribute by assigning a value to a variable name outside of .__init__().
- Use class attributes to define properties that should have the same value for every class instance.
- Use instance attributes for properties that vary from one instance to another.
- Instance methods are functions that are defined inside a class and can only be called from an instance of that class.
- Just like .__init__(), an instance method’s first parameter is always self.
- Methods like .__init__() and .__str__() are called dunder methods because they begin and end with double underscores.
- Inheritance is the process by which one class takes on the attributes and methods of another.
- Newly formed classes are called child classes, and the classes that child classes are derived from are called
parent classes.
- Inheritance is a way of creating a new class for using details of an existing class without modifying it.
- Encapsulation is one of the key features of object-oriented programming.
- Encapsulation refers to the bundling of attributes and methods inside a single class.
- Polymorphism is, the same entity (method or operator or object) can perform different operations in different scenarios.
- Uses of Inheritance:
- Since a child class can inherit all the functionalities of the parent's class, this allows code reusability.
- Once a functionality is developed, you can simply inherit it.
- No need to reinvent the wheel.
- This allows for cleaner code and easier to maintain.
- Since you can also add your own functionalities in the child class, you can inherit only the useful functionalities and define other required features.
### 클래스 생성자, 클래스 메소드
class myClass:
def __init__(self, x, y):
self.x = x
self.y = y
def myMethod(self):
print(f'This is myMethod -> x: {self.x}, y: {self.y}')
def main():
mc = myClass(1, 2)
mc.myMethod()
pass
if __name__ == '__main__':
main()
# 결과
This is myMethod -> x: 1, y: 2
### 스태틱 필드의 사용 (사실 함수와 다를게 없다)
class UseStaticField:
result = []
def __init__(self, *args):
ret = []
c = random.randint(0, 1)
for arg in args:
if c == 0 and arg % 2 == 0:
ret.append(arg)
if c == 1 and arg % 2 == 1:
ret.append(arg)
UseStaticField.result = ret
def getResult(self):
return UseStaticField.result
def main():
u1 = UseStaticField(1, 2, 3, 4, 5)
print(u1.getResult())
u2 = UseStaticField(0, 7, 10, 23)
print(u2.getResult())
pass
if __name__ == '__main__':
main()
#결과 1
[2, 4]
[0, 10]
#결과 2
[1, 3, 5]
[7, 23]
### 클래스 메쏘드로 쪼갠 버전
import random
class ChoiceNums:
inList = []
outList = []
def __init__(self, *args):
ChoiceNums.inList.clear()
for arg in args:
ChoiceNums.inList.append(arg)
def getEvens(self):
ChoiceNums.outList.clear()
for e in ChoiceNums.inList:
if e % 2 == 0:
ChoiceNums.outList.append(e)
return ChoiceNums.outList
def getOdds(self):
ChoiceNums.outList.clear()
for e in ChoiceNums.inList:
if e % 2 == 1:
ChoiceNums.outList.append(e)
return ChoiceNums.outList
def main():
u1 = ChoiceNums(1, 2, 3, 4, 5)
print('even:', u1.getEvens())
print('odd:', u1.getOdds())
print('\t')
u2 = ChoiceNums(0, 7, 10, 23)
print('even:', u2.getEvens())
print('odd:', u2.getOdds())
pass
if __name__ == '__main__':
main()
# 결과
even: [2, 4]
odd: [1, 3, 5]
even: [0, 10]
odd: [7, 23]
### 객체 안의 데이터를 사용한 버전
class selectNums:
def __init__(self, *args):
self.args = args
self.ret = []
def getEvens(self):
self.ret.clear()
for e in self.args:
if e % 2 == 0:
self.ret.append(e)
return self.ret
def getOdds(self):
self.ret.clear()
for e in self.args:
if e % 2 == 1:
self.ret.append(e)
return self.ret
def main():
u1 = selectNums(1, 2, 3, 4, 5)
print('even:', u1.getEvens())
print('odd:', u1.getOdds())
print('\t')
u2 = selectNums(0, 7, 10, 23)
print('even:', u2.getEvens())
print('odd:', u2.getOdds())
pass
if __name__ == '__main__':
main()
# 결과
even: [2, 4]
odd: [1, 3, 5]
even: [0, 10]
odd: [7, 23]
### 리스트 컴프리헨션으로 객체 내부에 리스트 유지 X
class selectNums:
def __init__(self, *args):
self.args = args
def getEvens(self):
return [e for e in self.args if e % 2 == 0]
def getOdds(self):
return [e for e in self.args if e % 2 == 1]
def main():
u1 = selectNums(1, 2, 3, 4, 5)
print('even:', u1.getEvens())
print('odd:', u1.getOdds())
print('\t')
u2 = selectNums(0, 7, 10, 23)
print('even:', u2.getEvens())
print('odd:', u2.getOdds())
pass
if __name__ == '__main__':
main()
# 결과
even: [2, 4]
odd: [1, 3, 5]
even: [0, 10]
odd: [7, 23]
# 클래스 속성과 인스턴스 속성 구별
class SProperty:
shared_ls = [] # 클래스 속성
def __init__(self, n):
self.shared_ls.append(n) # self로 지정해도 접근 가능
class PProperty:
def __init__(self):
self.private_ls = [] # 인스턴스 속성
def put(self, n):
self.private_ls.append(n)
def main():
s1 = SProperty('1')
s2 = SProperty('2')
print('-> 클래스 속성은 모든 인스턴스에 공유')
print('s1:', s1.shared_ls)
print('s2:', s2.shared_ls)
print('\t')
p1 = PProperty()
p1.put('3')
p2 = PProperty()
p2.put('4')
print('-> 인스턴스 속성은 인스턴스별로 독립')
print('p1:', p1.private_ls)
print('p2:', p2.private_ls)
pass
if __name__ == '__main__':
main()
# 결과
-> 클래스 속성은 모든 인스턴스에 공유
s1: ['1', '2']
s2: ['1', '2']
-> 인스턴스 속성은 인스턴스별로 독립
p1: ['3']
p2: ['4']
# 기본적인 상속의 예
class Person():
# 생성자
def __init__(self, name):
self.name = name
# get name
def getName(self):
return self.name
# employee 객체인지 체크
def isEmployee(self):
return False
class Employee(Person):
def isEmployee(self):
return True
def main():
e1 = Person('Big Boss')
print(e1.getName(), e1.isEmployee())
e2 = Employee('Ant worker')
print(e2.getName(), e2.isEmployee())
if __name__ == '__main__':
main()
#결과
Big Boss False
Ant worker True
### 다형성 함수의 간단한 예
def myAdd(x, y, z = 0):
return x + y + z
def main():
print(myAdd(1, 2))
print(myAdd(1, 2, 3))
if __name__ == '__main__':
main()
#결과
3
6
### 클래스 메서드의 다형성
class hero():
def say(self):
print("I'm hero.")
class villain():
def say(self):
print("I'm villain!")
def main():
h = hero()
v = villain()
for e in (h, v):
e.say()
if __name__ == '__main__':
main()
#결과
I'm hero.
I'm villain!
### 클래스 메서드와 스태틱 메서드의 사용
"""
1. We generally use the class method to create factory methods. Factory methods return class objects ( similar to a constructor ) for different use cases.
2. We generally use static methods to create utility functions.
"""
import datetime
class Person:
staticVar = 0
def __init__(self, name, age):
Person.staticVar += 1
self.name = name
self.age = age
def getName(self):
return self.name
@staticmethod
def getObjCount():
return Person.staticVar
@classmethod
def fromBirthYear(cls, name, year):
return cls(name, datetime.date.today().year - year)
def main():
p1 = Person('sally', 21)
p2 = Person.fromBirthYear('sally', 1996)
p3 = Person('danny', 30)
print(p1.getName(), p1.age)
print(p2.getName(), p2.age)
print(p3.getName(), p3.age)
print('\t')
print('obj count:', Person.getObjCount())
if __name__ == '__main__':
main()
#결과
sally 21
sally 27
danny 30
obj count: 3
댓글 영역