[Python] 파이썬 클래스 심화#2

아직·2022년 6월 8일
0
post-thumbnail

1)

print(car1._details.get('price')) #혹은 딕셔너리니까
print(car1._details['price'])

위와 같이 self인자를 갖는 instance 변수의 _details attribute의 price에 접근할 수 있지만 이렇게 '타고 내려가는 식'으로 그 때마다 접근하는 건 좋은 방법이 아니라서(현업에서는 아예 접근을 막아둔다고 한다.) get_price(self)라는 instance method를 작성한다.

2)

def get_price(self) 가 아닌 def get_price()로 정의하고 print(car1.get_price())로 값 불러올 경우
"TypeError: Car.get_price() takes 0 positional arguments but 1 was given" 에러가 발생한다. self 인자가 없이 정의된 instance method가 car1에 의해서 (생략되어 있는) self인자를 "given" 해버린 것이다. *class method는 @로 따로 정의하므로, 그렇지 않은 녀석들은 일단 self인자를 갖는/갖지 않는 instance method로 이해해보자.

https://velog.io/@magnoliarfsit/RePython-1.-self-%EC%9D%B4%ED%95%B4%ED%95%98%EA%B8%B0 참고

3)

Car.price_per_raise=1.4
print(car1.get_price_culc())

클래스 변수 또한 직접 접근하는 것은 좋은 방법이 아니므로 class method를 정의할텐데, instance method가 self인자를 default로 가지듯이 아래를 기본 형태로 이해하면 좋다.

	@classmethod
		def raise_price(cls)'

4)

instance method의 변수 self 자리에 다른 변수를 가질 수 있는 static method를 다음과 같이 정의했다.

	@staticmethod
    	def is_bmw(inst):
      		if inst._company == 'bmw':
       			return 'this car is {}'.format(inst._company)
        	return 'sorry this this car is not bmw

그런데 아래와 결과 차이가 없어서 활용을 고민해봐야겠다.

		def if_bmw(self):
       		 if self._company == 'bmw':
        	    return 'this car is {}'.format(self._company)
      	 	 return 'sorry this this car is not bmw

0개의 댓글