LoginSignup
2
0

pythonのclassとアトリビュート

Posted at

変数と関数

pythonの全てのものはオブジェクト

変数x:オブジェクトのインデックス(別名、お前に名前をつけてやる)
関数f(x):pythonオブジェクトを受け取ってpythonオブジェクトを吐き出すpythonオブジェクト(入力を受け取って出力を出すpythonオブジェクト)

構造体

pythonにはない
強いて言えばdataclass

構造体:変数の集合に名前を付けたもの
複数の変数が並んでる

@dataclass
class Student:
    name: string
    age: int
    major: string
    address: string
    birthday: int

# 使用例
student_hina = Student("hina", 20, "sleep", "Waseda", 20040323)

class

class:ひな型
構造体の中である処理をしたい!関数の機能を取り込んだ
関数と構造体がくっついているようなイメージ

class Student:
    def __init__(
        self,
        name: string
        age: int
        major: string
        address: string
        birthday: int
    ):
        # アトリビュート
        self.name=name
        self.age=age
        self.major=major
        self.address=address
        self.birthday=birthday

    # 関数
    def convert_to_japansese_calendar(self):
        return ""

# 使用例 インスタンス化
student_hina = Student("hina", 20, "sleep", "Waseda", 20040323)

classのインスタンス化
hoge = class名()
ひな型から実体を作る作業→__init__を呼んでいる

ダンダ―メソッド

def __init__はインスタンス化した際に呼ばれる

def __call__はインスタンス化した後に関数のように呼び出せる

hoge = Student()  # ここで__init__が呼び出される
hoge(<__call__の引数>)  # ここで__call__が呼び出される

def __getitem__はindexなどで何番目のものが欲しいと表記したときに呼ばれる

class Student:
    def __init__(
        self,
        name: string
        age: int
        major: string
        address: string
        birthday: int
    ):
        self.name=name
        self.age=age
        self.major=major
        self.address=address
        self.birthday=birthday
        
    def __getitem__(self, index):
        if index == 0:
            return self.name
        elif index == 1:
            return self.age
        else:
            raise IndexError

student_hina = Student("hina", 20, "sleep", "Waseda", 20040323)

print(student_hina[0])
"hina"
        

def __len__は長さを定義するときに使用する

アトリビュート

classの中のどこでも使える変数
self.hogehoge

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