자신
'self'라는 단어는 클래스의 인스턴스를 나타내는 데 사용됩니다. "self" 키워드를 사용하여 파이썬에서 클래스의 속성과 메소드에 액세스합니다.
__init__ 메소드
"__init__"은 파이썬 클래스에서 예약된 메서드입니다. 객체 지향 용어로 생성자라고 합니다. 이 메서드는 클래스에서 객체가 생성될 때 호출되며 클래스가 클래스의 속성을 초기화할 수 있도록 합니다.
예시
너비(b=120), 길이(l=160)인 직사각형 필드의 비용을 구하십시오. 비용은 1제곱 단위당 x(2000) 루피입니다.
class Rectangle:
def __init__(self, length, breadth, unit_cost=0):
self.length = length
self.breadth = breadth
self.unit_cost = unit_cost
def get_area(self):
return self.length * self.breadth
def calculate_cost(self):
area = self.get_area()
return area * self.unit_cost
# breadth = 120 units, length = 160 units, 1 sq unit cost = Rs 2000
r = Rectangle(160, 120, 2000)
print("Area of Rectangle: %s sq units" % (r.get_area())) 출력
이것은 출력을 제공합니다.
Area of Rectangle: 19200 sq units Cost of rectangular field: Rs.38400000