やりたいことに単純に回答するなら以下のように使いたい関数のあるクラスのインスタンスを生成し、インスタンス.関数名(引数)で使用することができます。
python
1class Sampel:
2 def __init__(self):
3 pass
4
5 def AAA(x,y):
6 print("hello world to {} and {}".format(x,y)
7 return 0
8
9class Sample2:
10 def __init__(self):
11 pass
12
13 def BBB(x,y):
14 #AAA(x,y) <-この中でAAAの関数を呼び出したいです
15 sampel = Sampel()#Class Sampelのインスタンス作成
16 sampel.AAA(x,y)
17
これは質問とは関係ないですが、関数に必ず返り値が必要な訳ではありませんので、AAAの関数のreturn 0はなくても良いです。書くなら return True などがよろしいかと。
あと、クラスを書くときにはコンストラクタ(厳密にはコンストラクタではないですが)を記述しましょう。
python
1class Sampel:
2
3 def __init__(self,x,y):
4 self.x = x
5 self.y = y
6
7 def AAA(self):
8 print("hello world to {} and {}".format(self.x,self.y)
9
10
11if __name__ == '__main__':
12 sampel = Sampel(1,2)
13 sampel.AAA()
14
このような書き方が一般的です。また、勘違いされてしまうかもしれないので説明しますが、クラスに所属していない関数は例え同じファイルに記述されていてもインスタンス作成せずに呼び出すことができます。
python
1class Sampel:
2
3 def __init__(self,x,y):
4 self.x = x
5 self.y = y
6
7 def AAA(self):
8 print("hello world to {} and {}".format(self.x,self.y)
9
10def helloWorld():
11 print("Hello World!")
12
13
14
15if __name__ == '__main__':
16 helloWorld()
17 sampel = Sampel(1,2)
18 sampel.AAA()
19
クラス関連についてまとめられたサイトはたくさんありますのでよく目を通しておくと良いですよ。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2017/05/28 07:53
2017/05/28 08:13