2018年10月4日木曜日

開発環境

  • macOS Mojave - Apple
  • Emacs (Text Editor)
  • Python 3.7 (プログラミング言語)

入門 Python 3 (Bill Lubanovic (著)、斎藤 康毅 (監修)、長尾 高弘 (翻訳)、オライリージャパン)の6章(オブジェクトとクラス)、6.15(復習問題)6-4、5、6、7、8.を取り組んでみる。

コード(Emacs)

Python 3

#!/usr/bin/env python3

print('4、5、6、7.')


class Element:
    def __init__(self, name, symbol, number):
        self.name = name
        self.symbol = symbol
        self.number = number

    def dump(self):
        print(
            f'name: {self.name}, symbols: {self.symbol}, number: {self.number}')

    def __str__(self):
        return f'name: {self.name}, symbols: {self.symbol}, number: {self.number}'


h1 = Element('Hydrogen', 'H', 1)
d = {'name': 'Hydrogen', 'symbol': 'H', 'number': 1}
h2 = Element(**d)
hs = [h1, h2]

for h in hs:
    h.dump()
    print(h)

print('8.')


class Element1:
    def __init__(self, name, symbol, number):
        self.__name = name
        self.__symbol = symbol
        self.__number = number

    @property
    def name(self):
        return f'name: {self.__name}'

    @property
    def symbol(self):
        return f'symbol: {self.__symbol}'

    @property
    def number(self):
        return f'number: {self.__number}'


h3 = Element1('Hydrogen', 'H', 1)
print(h3.name, h3.symbol, h3.number)

try:
    h3.name = 'Name'
except Exception as err:
    print(err)

入出力結果(Terminal, Jupyter(IPython))

$ ./sample2.py
4、5、6、7.
name: Hydrogen, symbols: H, number: 1
name: Hydrogen, symbols: H, number: 1
name: Hydrogen, symbols: H, number: 1
name: Hydrogen, symbols: H, number: 1
8.
name: Hydrogen symbol: H number: 1
can't set attribute
$

0 コメント:

コメントを投稿