OOP (Object Oriented Programming)
class Person:
# Initialize instance(object)
def __init__(self):
# Create attribute
# Assign value to 'self.attribute' in '__init__' method
self.hello = 'Hello'
def greeting(self):
# Using attributes inside a class
print(self.hello)
# Instanse = class()
# Create an instance to use the class
james = Person()
# Call method
james.greeting() # "Hello"
class Person:
def __init__(self, name, age, address):
self.hello = 'μλ
νμΈμ.'
self.name = name
self.age = age
self.address = address
def greeting(self):
print('{0} μ λ {1}μ
λλ€.'.format(self.hello, self.name))
maria = Person('λ§λ¦¬μ', 20, 'μμΈμ μμ΄κ΅¬ λ°ν¬λ')
maria.greeting() # μλ
νμΈμ. μ λ λ§λ¦¬μμ
λλ€.
print('μ΄λ¦:', maria.name) # λ§λ¦¬μ
print('λμ΄:', maria.age) # 20
print('μ£Όμ:', maria.address) # μμΈμ μμ΄κ΅¬ λ°ν¬λ
class Person:
def __init__(self):
self.name = 'judy.'
def greeting(self):
print(f'μλ
νμΈμ. μ λ {self.name} μ
λλ€.')
# Inherit class 'Person'
class Student(Person):
def study(self):
print('곡λΆνκΈ°')
james = Student()
james.greeting() # μλ
νμΈμ.
james.study() # 곡λΆνκΈ°
class Person:
def __init__(self, name, age, address, wallet):
self.name = name
self.age = age
self.address = address
self.__wallet = wallet # '__value' : private
def pay(self, amount):
self.__wallet -= amount # Only can access to private attribute with method in class
print('μ΄μ {0}μ λ¨μλ€μ.'.format(self.__wallet))
def __greeting(self): # '__function' : private
print('Hello')
def hello(self):
self.__greeting() # Can call private method in class
maria = Person('λ§λ¦¬μ', 20, 'μμΈμ μμ΄κ΅¬ λ°ν¬λ', 10000)
# Error : AttributeError: 'Person' object has no attribute '__wallet'
# Accessing private properties/methods is not allowed from outside the class
maria.__wallet -= 10000
maria.__greeting()
# Accessible using methods created within the class
maria.pay(3000)
ν΄λμ€ μ¬μ©νκΈ°
https://dojang.io/mod/page/view.php?id=2372
ν΄λμ€ μμ±, λ©μλ
https://dojang.io/mod/page/view.php?id=2378
ν΄λμ€ μμ μ¬μ©νκΈ°
https://dojang.io/mod/page/view.php?id=2384