개발을 JavaScript로 시작해 실무에 사용하고 있는데, 회사에서 Python도 쓸일이 생겼다.
TypeScript 개발자의 시선에서 Python의 다른점을 알아보고자 한다.
JS/TS 는 var / let / const로 변수와 상수를 선언해 준다. Python은 선언문이 없다
//node
let variable = 'Good boy';
console.log(variable)
#python
variable = 'Good body'
print(variable)
JS/TS는 코드 블록{ } 을 통해 함수를 생성한다. Python은 들여쓰기로 코드블록을 만들고 함수를 생성한다.
그 외에도 함수 선언문이 function과 def 로 상이하며, python은 : 을 통해 다음 들여쓰기가 함수로 시작된다는 것을 정의한다.
//node
function add(a, b) {
return a + b;
}
#python
def add(a, b):
return a + b
JavaScript는 자기 자신을 지칭하는 변수인 this 를 사용하지만, Python은 self를 사용한다. JS는 초기화 함수 선언시 this를 선언하지 않지만, Python은 self 를 필수로 선언해 줘야한다.
//node
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
// 객체 생성
const john = new Person("John", 25);
// 메서드 호출
john.greet();
#python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
# 객체 생성
john = Person("John", 25)
# 메서드 호출
john.greet()
JavaScript와 Python 둘다 기본적으로 if와 else로 조건문이 이뤄져 있다.
JavaScript에 else if는 Python의 elif로 대체된다.
// node
if (a > 100) {
console.log(a)
} else if(a > 50) {
console.log('a is not higher')
}
#python
if a > 100 :
print(a)
elif a > 50 :
print('a is not higher')