简体   繁体   English

Python 将字典分配给属性

[英]Python assign dictionary to property

i have a class a kind like this:我有一个像这样的 class :

class equipment():
     def __init__(self, l, d):
          self.length = {"desc": "Length of equipment", "val":l, "unit":"ft"}
          self.diameter = {"desc": "Diameter of equipment", "val":d, "unit":"inch"}

so im needing a constructor for the properties something line所以我需要一个属性的构造函数

class fisicalProp():
   def __init_(self, d, v, u)
       self.something = {"desc": "Diameter of equipment", "val":d, "unit":"inch"}

then i only call然后我只打电话

class equipment():
         def __init__(self, l, d):
              self.length = fisicalPropertie("Length of equipment",l, "ft"}
              self.diameter = fisicalPropertie("Diameter of equipment", d, "inch"}

can you help me to improve my code like that?你能帮我改进我的代码吗?

Why do you complicate this action?你为什么要把这个动作复杂化? If you use this class for several instances, you don't need to create dict here.如果您将此 class 用于多个实例,则无需在此处创建 dict。 Therefore, if are not going to use inheritance, don't need to use () with class definition因此,如果不打算使用 inheritance,则不需要使用 () 和 class 定义

class equipment:
    def __init__(self, length, len_units, diameter, dia_units):
        self.length = (length, len_units)
        self.diameter = (diameter, dia_units)

eq = equipment(1, "ft", 2, "inch")
print(eq.length, eq.diameter)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM