python原型结构,不工作

时间:2018-04-01 10:06:04

标签: python prototype

每当我打印c1对象时,它会打印:     < main .Car对象位于0x7fde8b29a240>

但是我添加了 str 方法,将其格式化为正确的字符串,为什么不打印可读字符串?

import copy


class Prototype:

    def __init__(self):
        # constructor method to create the object
        self._objects = {}

     def register_object(self, name, obj):
        # this method is used to register an object
        self._objects[name] = obj

     def unregister_object(self, name):
         # this method is used to unregister an object
         del self._objects[name]

     def clone(self, name, **attr):

         obj = copy.deepcopy(self._objects.get(name))
         obj.__dict__.update(attr)
         return obj


class Car:
     def __init__(self):
     self.name = "Skylark"
     self.color = "blue"
     self.options = "extra horsepower in engine"

     def __str__(self):

        return '{} | {} | {}'.format(self.name, self.color, self.options)


c = Car()
prototype = Prototype()
prototype.register_object('skylark',c)


c1 = prototype.clone('skylark')

print(c1)

1 个答案:

答案 0 :(得分:0)

代码中的缩进存在问题。我已经纠正了这个问题,也可以得到理想的答案。函数def的缩进略微偏离。在两个班级中。

我已将此文件称为 test.py

import copy


class Prototype:

    def __init__(self):
        # constructor method to create the object
        self._objects = {}

    def register_object(self, name, obj):
    # this method is used to register an object
        self._objects[name] = obj

    def unregister_object(self, name):
         # this method is used to unregister an object
        del self._objects[name]

    def clone(self, name, **attr):

        obj = copy.deepcopy(self._objects.get(name))
        obj.__dict__.update(attr)
        return obj


class Car:
    def __init__(self):
        self.name = "Skylark"
        self.color = "blue"
        self.options = "extra horsepower in engine"

    def __str__(self):
        return '{} | {} | {}'.format(self.name, self.color, self.options)


c = Car()
prototype = Prototype()
prototype.register_object('skylark',c)


c1 = prototype.clone('skylark')

print(c1)

当我运行文件

$ python test.py

输出结果为:

#Output: Skylark | blue | extra horsepower in engine
相关问题