무냐의 개발일지
[헷갈린다] Python Class 본문
| Object Oriented Programming
Class : blueprint for objects (Everything is object in Python)
attributes = state of an object (variables)
methods = behavior of an object (functions)
| Create Class
Class is Templates, and we need something to refer data of a particular object
Self is a stand-in for a particular object
Should me the first argument of any method
class MyCounter:
def set_count(self, n):
self.count = n
mc = MyCounter()
mc.set_count(5)
mc.count = mc.count + 1
print(mc.count)
class Employee:
pass
emp = Employee()
class Employee:
def set_name(self, new_name):
self.name = new_name <-name이라는 명령어를 부르면 이렇게 변경하겠다
emp = Employee ()
emp.set_name('Korel Rossi')
print(emp.name)
class Employee:
def set_name(self, new_name):
self.name = new_name
def set_salary(self, new_salary):
self.salary = new_salary
def give_raise(self, amount):
self.salary = self.salary + amount
def monthly_salary(self):
return self.salary / 12
emp = Employee()
emp.set_name('Korel Rossi')
emp.set_salary(50000)
mon_sal = emp.monthly_salary()
print(mon_sal)
__init__ method (Constructor) : called every time an.object is created
: set the default value for the attributes
| 속성(Attribute) 생성하는 2가지 방법
1. using the methods
2. define altogether using constructor (__init__)
Class 직접 짜보기
# Write the class Point as outlined in the instructions
import numpy as np
import math as mt
class Point:
def __init__(self,x=0.0,y=0.0):
self.x = x
self.y = y
def distance_to_origin(self):
return np.sqrt(self.x**2 + self.y**2)
def reflect(self,axis):
self.axis = axis
if axis == "x":
self.y = -self.y
elif axis == "y":
self.x = -self.x
else:
print("error!")
pt = Point(x=3.0)
pt.reflect("y")
print((pt.x, pt.y))
pt.y = 4.0
print(pt.distance_to_origin())
'데싸 추가 독학' 카테고리의 다른 글
회귀 모델의 종류!! (0) | 2024.02.01 |
---|---|
[캐글스터디] #2 House Price (Scatterplot, Boxplot) (0) | 2024.01.26 |
[캐글스터디] #2 House Price (왜도, 첨도, distplot, kde, concat) (0) | 2024.01.26 |
[SQL독학] <SQL로 시작하는 데이터 분석> 1-3장 (0) | 2024.01.17 |
[SQL로 시작하는 데이터분석] #1 PostGreSQL 로 CSV파일 IMPORT 해오기! (1) | 2024.01.13 |