관리 메뉴

Storage Gonie

6. Python 리스트 Comprehension 본문

웹개발/Django 웹서비스 개발(인프런)

6. Python 리스트 Comprehension

Storage Gonie 2019. 2. 7. 22:26
반응형

article.text for article in self.articles 방식으로 리스트를 생성할 수 있다.

class Text:
def __init__(self, str):
self.text = str

def __str__(self):
return "Text: " + self.text

class User:
num_users = 0 # class 변수

def __init__(self, name):
self.numArticle = 0 # instance 변수
self.name = name
self.articles = []
User.num_users += 1

def write(self, text):
self.articles.append(text)
self.numArticle += 1

def __str__(self):
return "User: %s %s" % (self.name, self.articles)
#return "User: %s %s" % (self.name, [article.text for article in self.articles]) 로 해주면 2번째 출력 결과가 나옴

t = Text("This is some text")
t2 = Text("This is some text2")
user = User('honux')

user.write(t)
user.write(t2)

print(t)
print(user, user.numArticle)

'''
Text: This is some text
User: honux [<__main__.Text object at 0x1032c50b8>, <__main__.Text object at 0x1032c50f0>] 2

Text: This is some text
User: honux ['This is some text', 'This is some text2'] 2
'''



반응형
Comments