2017-01-25 59 views
0

我有一个体检表类。这种形式将提供给男性和女性。当我实例化课堂时,我不想区分男性和女性。如果我能够以同样的方式实例化,无论性别如何,并提出同样的问题,无论性别如何,这将是非常好的。但将意识到这是愚蠢的问,如果一个男人怀孕的话,程序也将要么不问这个问题或者更好的打印并称这是无关紧要的问题,跳过它。 这是我有的基本代码。的Python 3.4继承

if male: 
    form = medForm("Bill") 
    form.MedHistory.isSmoking() 


if female: 
    form = medForm("Sarah") 
    form.MedHistory.isSmoking() 
    form.MedHistory.isPregnent() 


class maleSection(): 
    def isSmoking(self): 
    #some code here exactly same as female, so create a base class later 

class femaleSection(): 
    def isPregnent(self): 
    #some code here 

    def isSmoking(self): 
    #some code here exactly same as male, so create a base class later 

class medForm(maleSection, femaleSection): 
    def _init_(self, nameOfCustomer): 
     #At the moment not sure if I need anything here 

这两个if语句很丑。什么是处理这个最好的方法?另外我听说使用超级可能会很棘手,因此,如果可能的话,我想不要使用超级并保持简单。这是在Win7,Python 3.4上运行的。 sys.version_info(major = 3,minor = 4,micro = 3,releaselevel ='final',serial = 0)

谢谢任何​​帮助,谢谢。

+0

第一:安装Python 3.6,如果可能的话,从这里开始 - 没有理由继续使用老版本 – jsbueno

+0

Secon:使用'super'并没有什么棘手的问题 - 不使用它很麻烦。不要试图避免它。 – jsbueno

+0

欣赏的帮助,但我不能升级,太多的依赖。如果你能给我一个超级如何解决我的问题的例子,这将是非常好的。 – usustarr

回答

1

对于这类问题,最好的方法是利用继承。它为您节省了大量时间,特别是如果您以后需要更改某些内容。

尝试是这样的:

class patientSection(): 
     def isSmoking(self): 
      #the code here is the same for both male and female 

    class maleSection(patientSection): 
     #no code here, since we have access to isSmoking already 

    class femaleSection(patientSection): 
     #again, we have access to isSmoking 
     def isPregnant(self): 
      #something here 

,如果你要问只有性别中立的问题,你可以声明只是一个patientSection的实例;但是,您需要使用femaleSection来使用isPregnant方法。

+0

A. McKernan that't问题,一个问题解决者之间的区别。非常感谢您的帮助。我真的希望Python可能会有一些解决方法。 – usustarr

+0

@usustarr没问题,我很高兴我能帮助!祝你好运! –