圣诞快乐!
我试图生成一些代码,这些代码会使用用户提供的信息创建一种数据库。
我可以使用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()
感谢您的帮助!
答案 0 :(得分:2)
当然可以。 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()
顺便说一句,您在nome
和__init__
使用ask_components
但在name
使用summary
,将两者中的一个更改为另一个。