通常、クラス間でいくつかのメソッドを共有したいのでBook
、一般的なプロパティを持つクラスを作成してから、さまざまなメソッドを定義しChemistry
、からプロパティまたはメソッドを継承するクラスを作成できます。English
find
Book
class Books(object):
def __init__(self, dictionary):
self.input = dictionary
def commonMethod(self):
print 'This is a shared method'
class Chemistry(Books):
def find(self):
print 'This is a particular method'
class English(Books):
def find(self):
print 'This is other particular method'
chemistryBook = Chemistry({'hello': 'goodbye'})
chemistryBook.find()
# This is a particular method
EnglishBook = English({'hello': 'goodbye'})
EnglishBook.find()
# This is other particular method
アップデート
あなたのメッセージの最後の部分を読んでいません。多分これはあなたが望むものです:
class Books(object):
def __init__(self, dictionary):
self.input = dictionary
if len(dictionary) > 1:
print 'More than 1'
self.command = Chemistry(self.input)
else:
print 'Less or equal'
self.command = English(self.input)
class Chemistry(object):
def __init__(self, d):
self.d = d
def find(self):
print "Now you can manipulate your dictionary in Chemistry", self.d
class English(object):
def __init__(self, d):
self.d = d
def find(self):
print "Now you can manipulate your dictionary in English", self.d
book = Books({'hello': 'goodbye'})
book.command.find()
# Less or equal
# Now you can manipulate your dictionary in English {'hello': 'goodbye'}
book2 = Books({'hello': 'goodbye', 'one': 1})
book2.command.find()
# More than 1
# Now you can manipulate your dictionary in Chemistry {'hello': 'goodbye', 'one': 1}
基本的に、これは入力に応じて必要なクラスの特定のインスタンスを作成します。この場合、引数として渡す辞書の長さが 1 より大きい場合、Chemistry() のインスタンスが作成されます。それ以外の場合は、English() のインスタンスを作成します。その後、find メソッドを使用できます。