【问题标题】:Is it possible to create class with unknown attributes in Python? [duplicate]是否可以在 Python 中创建具有未知属性的类? [复制]
【发布时间】:2019-01-08 05:41:27
【问题描述】:

我正在学习 Python,我刚刚学习完课程的基础知识。这是我正在学习的第一门 OOP 语言,所以目前并非一切都非常清楚。反正。


我想知道是否可以在 Python (3.6) 中创建一个我们不知道一些对象属性的类(或者可能只有 2 或 3 个)。

例如,假设您想通过其属性定义一个分子,以便您可以在另一个程序中使用它们来建模或预测事物。您可以涉及的基本属性将是(例如)TemperatureMolecularWeightMolarVolume。但是,您也可以使用 20 个不同的参数轻松定义您的分子。但是,其中一些可能并不适用于每个分子,或者您目前可能不需要使用它们。 (即软件的第一个版本,...)。


问题:

我想知道 Python 3.x 中是否存在如下语法,以便该类能够准确地创建分子具有的参数数量。我认为定义数千个分子不存在的变量将花费大量内存空间...

class Molecule:

    def __init__(self, Temperature, MolecularWeight, MolarVolume, *properties):
        self.Temperature = Temperature
        self.MolecularWeight = MolecularWeight
        self.MolarVolume = MolarVolume
        self.*properties = *properties

我的目标是使用 .txt 文件来记录我的分子的属性(我有数千个),它们的属性按定义的顺序排序,这样当使用该类时,如果分子甲醇我们有 10 个参数前三个如前所述,然后该类将按顺序创建具有十个属性的分子“甲醇”。


否则,如果它不存在,我是否应该在默认情况下创建一个包含所有我想到的参数的类,并根据情况将其中一些参数视为无用?或者使用现有的更好的东西?

提前谢谢你

【问题讨论】:

    标签: python python-3.x class parameters


    【解决方案1】:

    您可以通过使用 keyword argumentssetattr 函数来做到这一点:

    class Molecule:
         def __init__(self, temperature, molecular_weight, molar_volume, **properties):
             self.temperature = temperature
             self.molecular_weight = molecular_weight
             self.molar_volume = molar_volume
             for k, v in properties.items():
                 setattr(self, k, v)
    

    我还对你的变量名 as is convention 进行了大写。那么

    m = Molecule(15, 7.5, 3.4, other_property=100)
    
    m.other_property  # returns 100
    

    【讨论】:

      【解决方案2】:

      你听说过字典吗?

      properties = {'A':'value', ... , 'ljkhasdfljkhasdfhj':'value'}
      

      如果添加一个名为getProperty( propertyName ) 的方法,则可以处理该属性不存在的事件:

      def getProperty ( propName ):
          try:
              return properties[propName]
          except KeyError:
              return "Something went wrong"
      

      字典键的值可以是任何类型。有关 mroe 的详细信息,文档在这里:https://docs.python.org/3/tutorial/datastructures.html#dictionaries

      【讨论】:

      • OP 特别要求使用一个类。 properties.get(propName, "Some indicator of failure") 也比这个解决方案更 Pythonic。如果确实需要字典,您可能还想查看 json loads
      猜你喜欢
      • 1970-01-01
      • 2014-06-11
      • 1970-01-01
      • 1970-01-01
      • 2011-04-09
      • 1970-01-01
      • 2016-05-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多