通常你还想在你的类之间共享一些方法,这样你就可以拥有一个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 方法。