2020년 8월 28일 금요일

python 상속

 class Parent():

    def __init__(self):
        print("부모 클래스")

        self.money = 50000000000

class Child_1():
    def __init__(self):
        print("첫번째 자식입니다.")
        print(self.money)

class Child_2():
    def __init__(self):
        print("두번째 자식입니다.")

Child_1()
Child_2()

첫번째 자식입니다.
두번째 자식입니다.



상속 받은 후

class Parent():
    def __init__(self):
        print("부모 클래스")

        self.money = 50000000000

class Child_1(Parent):
    def __init__(self):
        super().__init__()
        print("첫번째 자식입니다.")
        print(self.money)

class Child_2(Parent):
    def __init__(self):
        print("두번째 자식입니다.")

Child_1()
Child_2()

부모 클래스
첫번째 자식입니다.
50000000000
두번째 자식입니다.


잘못된 상속

class Parent():
    def __init__(self):
        print("부모 클래스")

        self.money = 50000000000

class Child_1(Parent):
    def __init__(self):
        super().__init__()
        print("첫번째 자식입니다.")
        print(self.money)

class Child_2(Parent):
    def __init__(self): -------------- Super를 받지않음
        print("두번째 자식입니다.")
        print(self.money)

Child_1()
Child_2()

Traceback (most recent call last):
  File "C:/Users/ejdrm/PycharmProjects/untitled/Test.py", line 45in <module>
    Child_2()
  File "C:/Users/ejdrm/PycharmProjects/untitled/Test.py", line 42in __init__
    print(self.money)
AttributeError'Child_2' object has no attribute 'money'
부모 클래스
첫번째 자식입니다.
50000000000
두번째 자식입니다.




함수는 SUper없이 가져올수있음!!

#상속
class Parent():
    def __init__(self):
        print("부모 클래스")

        self.money = 50000000000
    def book(self):
        print("부모의 서재입니다.")

class Child_1(Parent):
    def __init__(self):
        super().__init__()
        print("첫번째 자식입니다.")
        print(self.money)


class Child_2(Parent):
    def __init__(self):
        print("두번째 자식입니다.")
        self.book() ############가능하다

Child_1()
Child_2()


부모 클래스
첫번째 자식입니다.
50000000000
두번째 자식입니다.
부모의 서재입니다.

python class 기초

 #class 기초

#클래스는 구분하기위한 용도로 맨 앞글자는 대문자로 쓴다
class B_school():
def __init__(self):
print("B클래스 입니다")

self.student_name = "원빈"

class A_school():
def __init__(self):
print("A클래스 입니다")
bb = B_school()

self.student_name_a =bb.student_name;
print(self.student_name_a)


#B_school().stock()
A_school()

2020년 8월 27일 목요일

Python - 함수의 인자로 함수전달

 c#에서는 복잡한 이 기능이 python에서는 아주 단순하다.


ex

def english():
print("영어과 입니다")


def math(name,eng):
print("수학과 입니다.")
eng() ->해당받은 인자를 실행해준다


#3 - 함수의 인자로 함수 전달
math(name='원빈',eng=english)

수학과 입니다.
영어과 입니다



잘못된 예

ex

def english():
print("영어과 입니다")


def math(name,eng):
print("수학과 입니다.")
eng() ->해당받은 인자를 실행해준다 # 에러발생


#3 - 함수의 인자로 함수 전달
math(name='원빈',eng=english()) =>이런식으로 여기서 실행해버리면 에러가 난다.

영어과 입니다
수학과 입니다.
Traceback (most recent call last):
  File "C:/Users/ejdrm/PycharmProjects/week1/basic/python.py"line 23in <module>
    math(name='원빈',eng=english())
  File "C:/Users/ejdrm/PycharmProjects/week1/basic/python.py"line 19in math
    eng()
TypeError'NoneType' object is not callable



    

2020년 8월 26일 수요일

c#에서 외부파일 실행하기

 리스트 과제에서 외부 파이선을 실행해야하는 상황이 생겨서 해본것


%주의 -> 왠만한 에러는 콘솔창에 나오게 할수 있지만 

나오지 않는 에러도 있으니 차근차근 디버깅 해야함(호출하는곳,실행되는곳)

실행되는 원본(파이썬)에서는 에러 없이 되지만 호출하여서 인자를 받아서 실행할때는 안될수도있다.

인자를 통하여 외부프로그램이 돌아가는지 하나씩 확인하여 디버깅하여야한다.




//호출부분


public void PythonStart(string key, string data, int TotalLen, string PATH_p)

        {

            var psi = new ProcessStartInfo();

            Console.WriteLine("PATH_p:" + PATH_p);

            Console.WriteLine("data:" + data);

            //string psi_args = PATH_p + data; //경로를 지정한 실행파일


            string[] dataitem = data.Split(' ');

            dataitem[3] =dataitem[3].Replace("'", "");

            dataitem[4] =dataitem[4].Replace("'", "");

            dataitem[5] = dataitem[5].Replace("'", "");

            string newresult = "";

            for (int i = 0; i < dataitem.Length; i++)

            {

                newresult += dataitem[i]+" ";

            }

            string psi_args = PATH_p + newresult; //경로를 지정한 실행파일

            //string psi_args = PATH_p + data; //경로를 지정한 실행파일

            Console.WriteLine("psi_args:" + psi_args);

            psi.FileName = @"C:\scheduler\rist_env\Scripts\python.exe"; //파이썬 가상환경 설치 경로

            psi.Arguments = psi_args; //파일경로

            //psi.Arguments = string.Format("\"{0}\"\"{1}\"", PATH_p, data);


            //3) Proecss configuration

            psi.UseShellExecute = false;

            psi.CreateNoWindow = true;

            psi.RedirectStandardOutput = true;

            psi.RedirectStandardError = true;


            //4) return value def

            var errors = ""; // 출력은 하지 않습니다.

            var results = "";


            //using (var process = Process.Start(psi))

            //using (var process = System.Diagnostics.Process.Start(psi))

            using (var process = Process.Start(psi))

            {

                Console.WriteLine("프로세스 실행 하고 기다리기!!");

                //process.WaitForExit();


                results = process.StandardOutput.ReadToEnd();

                errors = process.StandardError.ReadToEnd();

                RxBox.AppendText("Error : " + errors + Environment.NewLine);

                RxBox.AppendText("Result : " + results + Environment.NewLine);

                //while (process.StandardOutput.Peek() > -1)

                //{


                //    process.StandardOutput.Close();

                //    RxBox.AppendText("break!!!! process.StandardOutput.Peek()");

                //    break;

                //}

                //while (process.StandardError.Peek() > -1)

                //{


                //    process.StandardError.Close();

                //    RxBox.AppendText("process.StandardError.Peek()");

                //    break;

                //}


                //using (StreamReader reader = process.StandardOutput)

                //{

                //    results = reader.ReadToEnd();

                //    Console.WriteLine(results);

                //}

                //using (StreamReader reader = process.StandardError)

                //{

                //    errors = reader.ReadToEnd();

                //    Console.WriteLine(errors);

                //}

            }

            

            RxBox.AppendText("Error : " + errors + Environment.NewLine);

            RxBox.AppendText("Result : " + results + Environment.NewLine);

        }







//키받아서 외부로 보내는것 관리하는 함수

try

                    {

                        switch (key)

                        {

                            case "predict_schedule_to_db":

                                Console.WriteLine("predict_schedule_to_db 요청 들어옴");

                                //path = @"C:\scheduler\pzpy\rist\app\predict_schedule_to_db.py";

                                path = $"\"C:\\scheduler\\pzpy\\rist\\app\\predict_schedule_to_db.py\"";

                                Form1.instance.PythonStart(key, value.Substring(1, value.Length - 1), e.RawData.Length, path);

                                //Form1.instance.PythonTest(key, value.Substring(1, value.Length - 1), e.RawData.Length, path);

                                break;

                            case "verify_model":

                                Console.WriteLine("verify_model 요청 들어옴");

                                //path = @"C:\scheduler\pzpy\rist\app\verify_model.py";

                                path = $"\"C:\\scheduler\\pzpy\\rist\\app\\verify_model.py\"";

                                Form1.instance.PythonStart(key, value.Substring(1, value.Length - 1), e.RawData.Length, path);

                                //Form1.instance.PythonTest(key, value.Substring(1, value.Length - 1), e.RawData.Length, path);

                                break;


                            case "test_hubiz":

                                Console.WriteLine("test_hubiz 요청 들어옴");

                                path = $"\"C:\\scheduler\\pzpy\\rist\\app\\test_hubiz.py\"";

                                Form1.instance.PythonStart(key, value.Substring(1, value.Length - 1), e.RawData.Length, path);

                                //Form1.instance.PythonTest(key, value.Substring(1, value.Length - 1), e.RawData.Length, path);

                                break;

                        }

                        //맨앞에 공백 하나 제거

                        //Form1.instance.PythonTest(key, value.Substring(1, value.Length-1), e.RawData.Length, path);

                        

                    }

                    catch (Exception ex)

                    {

                        MessageBox.Show(ex.ToString());

                        return;

                    }

2020년 8월 25일 화요일

[Python] Error Non-UTF-8 code starting with '\xeb',해결방법

해당 에러가 발생하면 

밑에 코드를 위에 적어주면 된다
#!/usr/bin/python
# -*- coding: utf-8 -*-

2020년 8월 22일 토요일

[Unity] Interface, 유니티 인터페이스 사용예제


인터페이스를 사용하면 이런 코드를

public class Bullet : MonoBehaviour{

    private void OnTriggerEnter2D(Collider2D collider)
    {
        Enemy enemy = collider.GetComponent<Enemy>();
        if(enemy != null)
        {
            //Hit a Enemy
            enemy.Damage();            
        }

        Crate crate = collider.GetComponent<Crate>();
        if(crate != null)
        {
            //Hit a Crate
            crate.Damage();            
        }

    }

}

매우간단하게 이런식으로

public Interface IDamageable{

    void Damage();
}

인터페이스를 추가하고


public class Enemy : MonoBehaviour , IDamageable{

    public void Damage();
}

public class Crate : MonoBehaviour , IDamageable{

    public void Damage();
}



이런식으로 변경할수있다.

public class Bullet : MonoBehaviour{

    private void OnTriggerEnter2D(Collider2D collider)
    {
       IDamageable damageable = collider.GetComponent<IDamageable>();

        if(damageable != null)
        {
            //Hit a Damageable Object
            damageable.Damage();
        }
    }

} 


원하는 어떤객체든지 IDamageable을 상속시키면 모두 사용가능하다




git rejected error(feat. cherry-pick)

 문제 아무 생각 없이 pull을 받지않고 로컬에서 작업! 커밋, 푸시 진행을 해버렷다. push에선 remote와 다르니 당연히 pull을 진행해라고 하지만 로컬에서 작업한 내용을 백업하지 않고 진행하기에는 부담스럽다(로컬작업 유실 가능성) 해결하려...