본문 바로가기

파이썬 TIP/라이브러리

collections > UserList

UserList

list 객체를 상속 받아 기능을 확장할 때 사용한다.

1. UserList를 상속하여 list를 생성

 

1) 클래스 생성

class MyList(UserList): 
   def __init__(self, *args, **kwargs) : 
       super().__init__(*args, **kwargs )

 

2) 기능 테스트

mylist = MyList()
mylist.append(1) 
mylist.append(2) 
mylist.append(3) 
mylist 
>> MyList([1, 2, 3])

mylist = MyList('mylist') 
mylist 
>> MyList(['m', 'y', 'l', 'i', 's', 't'])

2. 기능을 추가해서 확장

 

1) 클래스 생성

class MyList(UserList):
 def __init__(self, *args, **kwargs) :        
     super().__init__(*args, **kwargs )

# 입력된 데이터의 합을 반환한다.
 @property
 def sum(self,):  return np.sum(super().__dict__.get('data'))

 # 입력된 데이터의 평균을 반환한다.
 @property
 def mean(self):  return np.mean(super().__dict__.get('data'))

#입력된  데이터의 분산을 반환한다.
 @property
 def var(self): return np.round(np.var(super().__dict__.get('data')),2)

 

2) 기능 테스트

mylist = MyList()
mylist.append(1)
mylist.append(2)
mylist.append(3)

mylist.sum
>> 6

mylist.mean
>> 2.0

mylist.var
>> 0.67

참고: Python 3.x 문서
URL: https://docs.python.org/ko/3.10/library/collections.html#collections.UserList

'파이썬 TIP > 라이브러리' 카테고리의 다른 글

주피터 노트북 아나콘다 연결  (0) 2023.02.07
zipline-reloaded 환경 생성  (0) 2023.02.07
typing > type hint  (0) 2022.01.08
Alphalens 설치  (0) 2022.01.03
Ta-Lib설치 (Colab)  (0) 2022.01.03