Python:使用通用属性管理多个类(通过序列化)

时间:2018-10-12 11:54:17

标签: python class inheritance properties deserialization


我是刚开始构建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未知吗?应该在解码器中进行检查吗?)。

非常感谢。

1 个答案:

答案 0 :(得分:0)

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

如果不同的子类具有相同方法的版本,则不需要链。

符合以下条件的事物:

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())