0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Built-in Function

Posted at

PythonのBuilt-in Function について

**Built-in Function(ビルトイン関数)**とは、Pythonにあらかじめ組み込まれている関数のことです。これらの関数は、インポートなどの準備をすることなく、どのPythonプログラムでもすぐに使用できます。


1. Built-in Functionとは?

  • Pythonにデフォルトで用意されている便利な関数群。
  • 簡単な処理から高度な操作まで対応可能。

print("Hello, World!")  # 出力
len("Hello")            # 文字列の長さを取得
type(42)                # データ型を取得

2. Built-in Function の特徴

  • 簡単に利用可能:
    • 特別なモジュールのインポートは不要。
  • 幅広い機能:
    • 入出力(例: print)、データ型チェック(例: type)、データ変換(例: intstr)など多数。
  • 高いパフォーマンス:
    • Pythonの実装に最適化されているため、効率的。

3. 主なBuilt-in Function

以下はよく使われるBuilt-in Functionの例です。

1. print()

  • オブジェクトをコンソールに出力します。
print("Hello, World!")
出力
Hello, World!

2. type()

  • オブジェクトのデータ型を返します。
print(type(42))       # 整数型
print(type("Hello"))  # 文字列型
出力
<class 'int'>
<class 'str'>

3. id()

  • オブジェクトの一意なID(メモリ上のアドレス)を返します。
x = "hello"
print(id(x))
出力
140703354255984  # 実際の値は環境に依存します

IDが同じ表示になる場合

  • Pythonでは、イミュータブルなオブジェクト(例: 文字列や数値)に対して同じ値が再利用される場合があります。
  • この仕組みを**インターンニング(interning)**と呼び、メモリの効率を高めるために使用されます。
x = "hello"
y = "hello"
print(id(x))  # xのID
print(id(y))  # yのID: xと同じになる
出力
140703354255984
140703354255984

なぜIDが同じになるのか?

  • Pythonは「文字列 'hello' がすでにメモリにある」と判断し、新しいメモリを確保せず、既存のメモリを再利用します。
  • このように、同じ値を持つオブジェクトが同じメモリアドレスを共有する場合があります。

4. len()

  • オブジェクト(文字列、リストなど)の長さを返します。
print(len("Hello"))    # 文字列の長さ
print(len([1, 2, 3]))  # リストの長さ
出力
5
3

5. int() / str()

  • 型変換を行うための関数です。

例: 数値に変換

print(int("42"))  # 文字列 "42" を整数に変換
出力
42

例: 文字列に変換

print(str(42))  # 整数 42 を文字列に変換
出力
"42"

6. isinstance()

  • オブジェクトが特定の型であるかを確認します。
x = 42
print(isinstance(x, int))  # True
出力
True

4. Built-in Functionのメリット

  1. 簡単に利用できる:
    • 初心者でも使いやすい構文。
  2. 豊富な機能:
    • シンプルな処理から高度な操作まで幅広く対応。
  3. 学習コストが低い:
    • ドキュメントやチュートリアルが豊富で、すぐに習得可能。

5. 実際の活用例

以下のような場面で、Built-in Functionが活躍します。

例: 型チェックと型変換

x = "42"
if isinstance(x, str):
    x = int(x)  # 文字列を整数に変換
print(x + 10)  # 計算可能
出力
52

6. Built-in Functionの完全リスト

Pythonには100以上のBuilt-in Functionがあります。以下のリンクから公式ドキュメントを確認できます:
Python Built-in Functions Documentation


7. まとめ

  • Built-in Function は、Pythonに組み込まれた便利な関数群です。
  • 簡単に利用できるため、プログラミングを効率化します。
  • よく使われる関数を覚えるだけで、コードの生産性が大幅に向上します。

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?