-
카테고리
-
세부 분야
프로그래밍 언어
-
해결 여부
미해결
property 사용시 동명의 속성이 이미 존재하면 어떻게 되나요?
22.12.09 22:02 작성 조회수 133
0
class Sample2:
def __init__(self):
self.x = 0
# self.y = 0 <<< ???
self.__y = 0
@property
def y(self):
print("I am getter!")
return self.__y
@y.setter
def y(self, value):
print("I am setter!")
if value < 0:
raise ValueError("y must be bigger than 0")
self.__y = value
return self.__y
@y.deleter
def y(self):
print("Goodbye")
del self.__y
위 코드처럼 __y에 대한 property와 setter를 작성하려면 데코레이터 부분과 함수의 이름에 __y의 언더스코어를 제외한 y만 사용하면 된다고 말씀하셨는데, 만약 이미 y라는 이름을 가진 속성이 있다면 어떻게 동작하나요? 단순히 안티패턴이니 사용하지 않으면 되는걸까요?
답변을 작성해보세요.
1
좋은사람
지식공유자2022.12.10
안녕하세요. 별도로 생성됩니다.
print(Sample2.__dict__)
print(dir(Sample2))
출력 후 확인해 보세요!
{'__module__': '__main__', '__init__': <function Sample2.__init__ at 0x7f4680735dc0>, 'y': <property object at 0x7f468073af90>, '__dict__': <attribute '__dict__' of 'Sample2' objects>, '__weakref__': <attribute '__weakref__' of 'Sample2' objects>, '__doc__': None}
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'y']
>
답변 1