2018年4月26日木曜日

開発環境

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

コード(Emacs)

Python 3

#!/usr/bin/env python3

print('6-4')


class Element:

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


hydrogen = Element('Hydrogen', 'H', 1)
print(hydrogen)

print('6-5')
d = dict(name='Hydrogen', symbol='H', number=1)
print(d)
hydrogen = Element(**d)
print(hydrogen)

print('6-6')


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}, symbol: {self.symbol}, number: {self.number}')

hydrogen = Element(**d)
hydrogen.dump()

print('6-7')


class Element:

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

    def __str__(self):
        return f'name: {self.name}, symbol: {self.symbol}, number: {self.number}'
hydrogen = Element(**d)
print(hydrogen)

print('6-8')


class Element:

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

    @property
    def name(self):
        return self.__name

    @name.setter
    def name(self, val):
        self.__name = val

    @property
    def symbol(self):
        return self.__symbol

    @property
    def number(self):
        return self.__number

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

hydrogen = Element(**d)
print(hydrogen)
print(hydrogen.name)
hydrogen.name = 'hydrogen'
print(hydrogen.name)
print(hydrogen)
print(hydrogen.symbol)
try:
    hydrogen.symbol = 'h'
except Exception as err:
    print(type(err), err)

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

$ ./sample2.py
6-4
<__main__.Element object at 0x104eaed30>
6-5
{'name': 'Hydrogen', 'symbol': 'H', 'number': 1}
<__main__.Element object at 0x104eaeda0>
6-6
name: Hydrogen, symbol: H, number: 1
6-7
name: Hydrogen, symbol: H, number: 1
6-8
name: Hydrogen, symbol: H, number: 1
Hydrogen
hydrogen
name: hydrogen, symbol: H, number: 1
H
<class 'AttributeError'> can't set attribute
$

0 コメント:

コメントを投稿

Comments on Google+: