반응형
from Test.Tester import Tester

class OperatorStep_1(Tester):

    def __init__(self):
        super().__init__(self.Test)
        pass

    def DoCalc(self, func):
        if callable(func):
            print(f"{func()}")

    def Test(self):

        # 사칙연산
        self.DoCalc(lambda :1+1)
        self.DoCalc(lambda :10 - 8)
        self.DoCalc(lambda :10 * 10)
        self.DoCalc(lambda :10 / 3) # 나눈 값
        self.DoCalc(lambda :10 / 10)
        self.DoCalc(lambda : 0x00001 & 0x00001) # AND 연산
        self.DoCalc(lambda : 0x00011 | 0x00001) # or 연산
        self.DoCalc(lambda : 0x00011 ^ 0x00001) # XOR 연산
        # 독특한 연산자들 [shift  연산 등등]
        self.DoCalc(lambda :10 << 1)
        self.DoCalc(lambda :10 >> 1)
        self.DoCalc(lambda :10 // 3) # 몫
        self.DoCalc(lambda :10 ** 2) # 제곱승 [ex : 10의 2승]

        # True, False
        self.DoCalc(lambda : 10 == 10)
        self.DoCalc(lambda : 10 >= 100)
        self.DoCalc(lambda : True | False)
        self.DoCalc(lambda : True and False)
        self.DoCalc(lambda : True is not True)
        self.DoCalc(lambda input=[1, 2, 3, 4, 5]: 1 in input) #특정 요소가 안에 있는지 여부
        a = 'test'
        self.DoCalc(lambda b = a: a == b) # 동일 참조 비교

        self.FinTest()
        pass

    pass

 

더보기

결과

 

 

2
2
100
3.3333333333333335
1.0
1
17
16
20
5
3
100
True
False
True
False
False
True
True
Test finish request

Test is finish


Process finished with exit code 0

 

 

* lambda란 무엇인지 알아보자.

반응형

'Python > Python Script' 카테고리의 다른 글

Printer.py - string format 연습  (0) 2020.06.22
개인 연습, 공부용 뼈대 코드  (0) 2020.06.22
문법 정리- sequence type  (0) 2020.05.28
Posted by Sweetmeats_boy
반응형

proj

 - Test

   ...

    L Printer.py

 

from Test.Tester import Tester


class Printer(Tester):

    def __init__(self):
        super().__init__(self.PrintTest)
        pass

    def PrintTest(self):
        """
        각종 string formatting들
        :return:
        """
        test_str = []
        #일반 문자열
        test_str.extend(
            [
                "This is basic print"
            ]
        )
        #% 연산자 활용방식, 단 args들의 타입을 정확히 명시해줘야함, 인자 많아질수록 코드 더러워짐
        test_str.extend(
            [
                "This way using operator %s %i" % ("haha", 2)
            ]
        )
        # C#에서도 쓰는 formatting
        # 인자 숫자에 맞춰 출력해주거나 아예 생략도 가능하다.
        # 다만 이방식도 다소 장황해질 수 있다.
        test_str.extend(
            [
                "This is basic formatting - {1}{0}".format("hehehe", 100),
                'For simple {}-{}'.format("hoomba", "HOOMBA"),
            ]
        )

        #개인적으론 제일 좋은것 같다.
        # f-string 이라고 하며, 3.6버전 이상부터 지원한다고 한다.
        reply = 'yes captain'
        f_str = f'Hmm interesting {reply}'

        test_str.extend([
            f_str,
        ])

        for ele in test_str:
            print(ele)
        input_val = input("press any key")
        self.FinTest()
        pass
    pass

python에서 지원하는 string format에 대한 연습 코드.

* list의 extend와 append에는 차이가 있으니 검색해볼것.

더보기

====결과

Hmm interesting yes captain
This is basic print
This way using operator haha 2
This is basic formatting - 100hehehe
For simple hoomba-HOOMBA
Hmm interesting yes captain
press any key

 

 

# test 결과 확인 후 임의의 입력 후 엔터누르면 종료됨.

반응형

'Python > Python Script' 카테고리의 다른 글

OperatorStep_1 - 각종 연산자 관련 코드.  (0) 2020.06.22
개인 연습, 공부용 뼈대 코드  (0) 2020.06.22
문법 정리- sequence type  (0) 2020.05.28
Posted by Sweetmeats_boy
반응형

해당 post는 특별한 건 없고, 단순히 개인적으로 공부할 때 사용하는 코드 구조이다.

 

project directory는 아래와 같다.

 

proj

 - Test 

    L Tester.py

    L TestFactory.py

 L main.py

 

우선 test 코드는 Tester.py 를 상속한 개별 class를 통해 진행하며, 

어떠한 Test를 진행할 지는 main.py에서 변수를 지정해주는 식이다.

# TestFactory.py



from Test.Tester import Enum
from Test.Tester import ETest

from Test.Printer import *


class TestFactory():

    test_dic = {}

    @classmethod
    def Init_Tester(cls):
        """
           수행할 test 종류는 여기서 세팅
           :return:
           """
        cls.test_dic[ETest.PRINTER] = Printer().DoTest
        pass

    @classmethod
    def GetTester(cls, test_val:ETest):
        """
        Test class들의 DoTest 함수를 반환.
        :param test_val: 원하는 test 종류
        :return:
        """
        return cls.test_dic.get(test_val, (lambda: None))

    pass
# main.py



from Test.TestFactory import *

def DoTest():
    """
    원하는 test에 따라서 test_val 지정.
    :return:
    """
    TestFactory.Init_Tester()
    test = TestFactory.GetTester(ETest.PRINTER)
    test()
    pass


if __name__ == '__main__':
    DoTest()
    pass

#Tester.py


from enum import Enum

class Tester:

    def __init__(self, test_loop):
        self.is_test_continue = True
        self.test_loop = test_loop
        pass

    def DoTest(self):
        if callable(self.test_loop):
            while(self.is_test_continue):
                self.test_loop()
        else:
            print(f'test ret : {self.test_loop}')
        print('Test is finish')
        pass

    def FinTest(self):
        print('Test finish requested')
        self.is_test_continue = False
        pass

    pass


class ETest(Enum):
    NONE = 0,
    PRINTER = 1,
    pass

code를 보면 알겠지만 Tester class를 상속받은 객체들의 testloop를 호출하게 된다.

 

각 Test에 따라서 __init__에서 실제 TestLoop를 지정해주면 된다.

main에서 Tetser와 관련된 애들을 import 시키고 싶지 않았기 때문에 TestFactory를 통해서 함수를 호출하게 했다.

 -> 아직 특정 import를 은닉화 하는 방법을 못찾았기 때문에 main에서 TestFactory를 통해서 Test에 접근이 가능하다. 

추후 공부 겸 test code 작성 시 posting 할 예정이다.

반응형

'Python > Python Script' 카테고리의 다른 글

OperatorStep_1 - 각종 연산자 관련 코드.  (0) 2020.06.22
Printer.py - string format 연습  (0) 2020.06.22
문법 정리- sequence type  (0) 2020.05.28
Posted by Sweetmeats_boy
반응형

출처 : https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range

 

Built-in Types — Python 3.8.3 documentation

The following sections describe the standard types that are built into the interpreter. The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions. Some collection classes are mutable. The methods that add, subtract,

docs.python.org

sequence type : list, tuple, range

 

x in S : S 안에 x 원소가 있는지 여부를 반환한다.

x not in S : S 안에 x가 있는지 여부를 반환한다.

x + y : x의 원소와 y의 원소를 합친 시퀀스 type을 반환한다.

n * x 혹은 x * n(n 은 양의 정수) : x의 원소를 n배 늘린 결과를 반환한다.

 -> 단 이 때 원소가 mutable이라면 해당 원소가 깊은복사가 되지 않고  얕은 복사가 되기 때문에 주의를 요한다.

 -> ex

tmp_list = [[]] *3
tmp_list[0].append(3)
-> [[3], [3], [3]]
tmp_list = [[] for ele in range(3)]
tmp_list[0].append(1)
tmp_list[1].append(2)
tmp_list[2].append(3)
-> [[1], [2], [3]]

x[i] : i 인덱스에 있는 원소를 반환한다.

x[i : c] : i 인덱스부터 c 개 만큼의 원소들을 반환한다.

x[i : c : s] : i 인덱스부터 s간격만큼 c개를 반환한다.

tmp_list = [ele for ele in range(5)]
-> [0, 1, 2, 3, 4 ]

tmp_list[1]
-> 1

tmp_list[0:2]
-> 0 1 

tmp_list[0:2:3]
-> 0

tmp_list[0:4:2]
-> 0 2 

tmp_list[0:5:2]
-> 0 2 4 

len(x) : x의 원소 갯수를 반환한다.

min(x), max(x) : x의 원소들의 비교를 통해서 최소원소, 혹은 최대 우너소를 반환한다.

x.count(ele) : x의 원소중 ele과 같은 원소들의 갯수를 반환한다. 

 

반응형
Posted by Sweetmeats_boy
이전버튼 1 이전버튼

블로그 이미지
Sweetmeats_boy

태그목록

Yesterday
Today
Total

달력

 « |  » 2025.2
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함