파이썬 클래스 객체 생성에 관한 질문
조회수 142회
acc_cus = []
dif = 0
while 1:
num = int(input(
"""
++++++++++++++++++++++++++++++
원하는 항목의 번호를 입력하세요.
1. 계정 생성
2. 입금
3. 출금
4. 계정 정보 확인
5. 종료
++++++++++++++++++++++++++++++
"""
))
class Bank:
def __init__(self,name):
self.name = name
self.account = [0]
def inform(self):
return "++++++++++++++++++++++++++++++\n"+"계정 이름: " + str(self.name) +"\n"+"잔고: " + str(self.account[0])+"원\n"+"++++++++++++++++++++++++++++++"
if num == 1:
name = input("""
++++++++++++++++++++++++++++++
계정의 이름을 입력하세요.
++++++++++++++++++++++++++++++
""")
dif += 1
"customer"+str(dif) = Bank(name)
fin = 'customer'+str(dif)
acc_cus.append(fin.name)
print(fin.inform())
print("""
++++++++++++++++++++++++++++++
계정 생성이 완료되었습니다.
++++++++++++++++++++++++++++++
""")
print("""
++++++++++++++++++++++++++++++
현재 계정 목록\n"""+str(acc_cus)+"\n++++++++++++++++++++++++++++++"
)
#(후략)
공부한지 1주정도 된 파이썬 왕초보 인데요.
여기서 객체를 생성할 때 인스턴스 이름을 custom1, custom2 이렇게 설정하고 싶은데, dif를 이때 1,2... 이렇게 설정해서 "custom"+str(dif)해서 연결하려고 하면 인스턴스 설정이 안됩니다. 무엇이 문제인가요?
2 답변
-
다음과 같이 변수를 넣어줘야 합니다.
b = "customer"+str(dif) a = Bank(name = b) print(a.name, a.account)
-
customer1 = Bank(name) customer2 = Bank(name) ...
이런 걸 하고 싶은 것 같습니다. 그런데, 이런 식으로 번호가 붙은 변수명은 별로 좋은 것이 아닙니다. 사람에게는 보이지만, 컴퓨터에게는 보이지 않아요.
배열의 인덱스로 접근하는 것이 원하는 방식일 겁니다.
customer = [] while True: name = input("name ?") customer.append(Bank(name)). ## customer[i] = Bank(name) print(customer[0]) print(customer[1])
댓글 입력