μƒˆμ†Œμ‹

Languages/Python

[Python] λ‹€ν˜•μ„±, property

  • -
λ°˜μ‘ν˜•
λ‹€ν˜•μ„± 

- 같은 λͺ¨μ–‘μ˜ μ½”λ“œκ°€ λ‹€λ₯Έ λ™μž‘μ„ ν•˜λŠ” 것

 

- μ½”λ“œμ˜ 양을 쀄이고, μ—¬λŸ¬ 객체 νƒ€μž…μ„ ν•˜λ‚˜μ˜ νƒ€μž…μœΌλ‘œ 관리가 κ°€λŠ₯ν•˜μ—¬ μœ μ§€ λ³΄μˆ˜μ— μ’‹λ‹€.

 

- λ©”μ†Œλ“œ μ˜€λ²„λΌμ΄λ”©λ„ λ‹€ν˜•μ„±μ˜ ν•œ 예

 

 

예제1)

#λ‹€ν˜•μ„± 예제 1
class Person:
    def __init__(self, name):
        self.name = name
 def work(self):
        print(self.name + " works hard")

clas
   s Student(Person):
    def work(self):
        print(self.name + ' studies hard')

class Engineer(Person):
    def work(self):
        print(self.name + "develope someting")

student = Student("Dave")
deceloper = Engineer("David")
student.work()
deceloper.work()

 

예제2)

# λ‹€ν˜•μ„± 예제 2
#클래슀 λͺ…λ§Œλ‹€λ₯΄κ³  μ•ˆμ— μžˆλŠ”λ‚΄μš©(λ©”μ†Œλ“œ) κ°€ κ°™μŒ. 관리가 맀우 μš©μ΄ν•¨.
class Elf:
    def __init__(self, name):
        self.name = name

    def attack(self):
        print("λ§ˆλ²• 곡격.")

class Fighter:
    def __init__(self,name):
        self.name = name

    def attack(self):
        print("주먹 곡격.")

elf = Elf("Dave")
fighter = Fighter('Anthony')
ourteam = [elf, fighter]
for attacker in ourteam:
    attacker.attack()

 

 

Porperty

 

예제 1)

# property 예제1
class Person():
    def __init__(self):
        self.__age = 0

    @property
    def age(self):
        return self.__age

    @age.setter
    def age(self, value):
        self.__age = value

james = Person()
james.age = 20 #μΈμŠ€ν„΄μŠ€.속성 ν˜•μ‹μœΌλ‘œ μ ‘κ·Όν•˜μ—¬ κ°’ μ €μž₯
print(james.age)# μΈμŠ€ν„΄μŠ€.속성 ν˜•μ‹μœΌλ‘œ 값을 κ°€μ Έμ˜΄


예제 2)

# property 예제2
class Person():
    def __init__(self):
        self.__name = 'hong'

    @property
    def name(self):
        return self.__name

    @name.setter
    def name(self, name):
        self.__name = name

person = Person()
print(person.name)
person.name = 'park'
print(person.name)

 

 

 

 

λ°˜μ‘ν˜•
Contents

ν¬μŠ€νŒ… μ£Όμ†Œλ₯Ό λ³΅μ‚¬ν–ˆμŠ΅λ‹ˆλ‹€

이 글이 도움이 λ˜μ—ˆλ‹€λ©΄ 곡감 λΆ€νƒλ“œλ¦½λ‹ˆλ‹€.