【问题标题】:Python: manage multiple classes (from serialization) with common propertiesPython:管理具有公共属性的多个类(来自序列化)
【发布时间】:2019-03-17 15:42:13
【问题描述】:


我是构建 Python 项目的新手,所以请原谅可能在这里写下的任何错误方法。

两个 JSON 方案代表两个对象。它们被序列化为类并具有共同的属性。

例子:

class TwoWheelVeicle(object):
    def __init__(self,v_family, v_subfamily):
        self.Family = v_family
        self.SubFamily = v_subfamily
        self.OtherProp = "other"

class FourWheelVeicle(object):
    def __init__(self,v_family):
        self.Family = v_family
        self.AnotherProp = "another"


def run_an_highway(vehicle):

    if isinstance(vehicle,FourWheelVeicle):
        return "Wrooom"

    if isinstance(vehicle,TwoWheelVeicle):
        if veichle.SubFamily in SubFams.NotAllowed:
            return "ALT!"
        else:
            return "Brooom" #forgive me for the sound


class SubFams(object):
    NotAllowed = ["Bicycle","50cc"]
    Known = ["200cc","Motorbike"]

我不太确定整个程序:
- 我应该创建一个抽象父类吗?
- NotAllowed 存储是否正确?这是由于需要更改其内容(即从一些全局参数 JSON 序列化,它是一个#TODO)

..或者只是我不想做这些?

最后,代码不允许任何检查我序列化的属性是否正确(如果 SubFamily 未知怎么办?应该在解码器中检查吗?)。

非常感谢。

【问题讨论】:

    标签: python class inheritance properties deserialization


    【解决方案1】:

    看起来您应该使用 Vehicle 类抽象车辆,然后为不同的车辆类型对其进行子类化。

    如果您的不同子类对同一方法有自己的版本,则不需要您的 if 链。

    与这些相符:

    class Vehicle(object):
        def __init__(self, name, cc):
            self.name = name
            self.cc = cc
            self.wheels = None
    
        def runs_on_highway(self):
            return self.cc > 50
    
        def sound(self):
            pass
    
    class TwoWheels(Vehicle):
        def __init__(self, name, cc):
            Vehicle.__init__(self, name, cc)
            self.wheels = 2
    
        def sound(self):
            return 'Brooom.'
    
    class FourWheels(Vehicle):
        def __init__(self, name, cc):
            Vehicle.__init__(self, name, cc)
            self.wheels = 4
    
        def sound(self):
            return 'Vruuum'
    
    class ElectricWheels(Vehicle):
        def __init__(self, name, cc):
            Vehicle.__init__(self, name, 0)
            self.wheels = 4
    
        def runs_on_highway(self):
            return True
    
        def sound(self):
            return 'zzzzz.'
    
    v1 = TwoWheels('Bicycle', 50)
    v2 = FourWheels('Motorbike', 200)
    v3 = ElectricWheels('ElectricBike', 0)
    
    print(v1.runs_on_highway())
    print(v2.runs_on_highway())
    print(v3.runs_on_highway())
    
    print(v1.name, v1.cc, v1.wheels, v1.sound())
    print(v2.name, v2.cc, v2.wheels, v2.sound())
    print(v3.name, v3.cc, v3.wheels, v3.sound())
    

    【讨论】:

    • 您的意思是 subFamily 的吸气剂,它在 FourWheelsVehicles 中返回 None? if vehicle.get_SubFam() in SubFams.NotAllowed 应该执行上述操作。还有..NotAllowed呢?
    • 不,@C.Claudio,我在想你可以像我刚刚发布的那样探索课堂安排。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-03
    • 2012-08-29
    • 1970-01-01
    • 2011-09-18
    • 2015-12-06
    • 2014-12-08
    相关资源
    最近更新 更多