【问题标题】:Can I ask the attributes of a class in a sub-definition?我可以在子定义中询问一个类的属性吗?
【发布时间】:2016-12-26 13:20:26
【问题描述】:

圣诞快乐!

我试图生成一些代码,这些代码将使用用户提供的信息创建一种数据库。 我可以使用input() 方法来定义我的实例变量吗?

class Compound:
def __init__(self, name, state, molecular_mass, concentration, concentration_measure):
    self.nome = name
    self.state = state
    self.mol_mass = molecular_mass
    self.conc = concentration
    self.measure = concentration_measure

def summary(self):
     return ('Your compound is {} it has a state of {} it has a molecular mass of {} g/mol and a concentration of {} and a measure of {}'
             .format(self.name, self.state, self.mol_mass, self.conc, self.measure))

def ask_compounds():
    self.nome = input("Name?")
    self.state = input('Solid or Liquid')
    self.mas_mol = input('Absolute number for molecular weight?')
    self.conc = input('Concentration?')
    self.measure = str(input('In M? In g/ml?'))

ask_compounds()

感谢您的帮助!

【问题讨论】:

    标签: python python-3.x class variables input


    【解决方案1】:

    当然可以。 return 输入的值并用它们初始化Compound 类:

    def ask_compounds():
        nome = input("Name?")
        state = input('Solid or Liquid')
        mas_mol = input('Absolute number for molecular weight?')
        conc = input('Concentration?')
        measure = input('In M? In g/ml?')
        return nome, state, mas_mol, conc, measure
    
    inst = Compound(*ask_compounds())
    

    或者,更好的是,将ask_compounds 设为为您创建实例的classmethod

    class Compound:
        def __init__(self, name, state, molecular_mass, concentration, concentration_measure):
            # snipped for brevity
    
        def summary(self):
             # snipped for brevity
    
        @classmethod
        def ask_compounds(cls):
            nome = input("Name?")
            state = input('Solid or Liquid')
            mas_mol = input('Absolute number for molecular weight?')
            conc = input('Concentration?')
            measure = input('In M? In g/ml?')
            return cls(nome, state, mas_mol, conc, measure)
    
    inst = Compound.ask_compounds()
    

    顺便说一句,您在__init__ask_components 中使用nome,但在summary 中使用name,将两者之一更改为另一个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-12
      • 2015-11-23
      • 1970-01-01
      • 2011-04-16
      • 2018-03-08
      • 2013-06-22
      • 1970-01-01
      相关资源
      最近更新 更多