LoginSignup
1
3

More than 5 years have passed since last update.

プログラマの考えが・・身につく本より(Python):クラス宣言(public/privateなど)

Last updated at Posted at 2016-05-26

こちらの書籍よりpythonでならどう書けるか?
プログラミングの考え方を勉強中。

第5章 クラスによる問題解決

こちらの内容でしたが、まずpythonのクラス設計を考えたことがなかったのでいろいろ検索しているとこちらQiitaに投稿されているとてもわかりやすい記事がありましたので参考にさせて頂きました。

最初に課題として「クラス宣言」がありましたのでpythonに書き換えてみました。

クラス宣言

test.cpp
class sample {
public:
    sample();
    sample(int num);
    int doesSomething(double param);

private:
    int intData;
};

こちらを考えるときに「public」「private」で分けて考えたことがなかったので参考サイトを参照して以下変えて動かしています

test501.py
#!/usr/bin/env python
#coding:utf-8

class Sample(object):

#public:
    #C++のsample()
    def sample1(self):
        print("sample")

    #C++のsample(int num)
    def sample2(self,r):
        return int(r)

    #C++のint doesSomething(double param)
    def doesSomething(self,param):
        return float(param)

##以下修正
    #private:
    __intData = 5  ### 呼び出しが _クラス名__変数名


>>>(ターミナル実行)
>>> from test501 import Sample
>>> w = Sample()
>>> w.sample1()
sample
>>> w.sample2(1)
1
>>> w.doesSomething(1.5)
1.5
>>> w._Sample__intData
5


最初、c++コードでは sample() もsample(1)も同じメソッド名で書いてあったのでpythonでも同じものを用意していたらエラーになり名前を変えることで動かせるようになりメソッド名の使い方も注意する点を気付かされました(´Д` )
カプセル化などテーマが続きますが、pythonのクラス設計はどうなっているのか引き続き勉強したいと思います。

1
3
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3