python原型结构,不工作

python原型结构,不工作,python,prototype,Python,Prototype,每当我打印c1对象时,它都会打印: 然而,我添加了str方法,以将其格式化为正确的字符串,为什么它不打印可读的字符串 import copy class Prototype: def __init__(self): # constructor method to create the object self._objects = {} def register_object(self, name, obj): # thi

每当我打印c1对象时,它都会打印:

然而,我添加了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)

代码中的缩进有问题。我已经纠正了这一点,也可以得到想要的答案。函数
def
s的缩进有点偏。在两个班里

我将此文件称为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

我无法重现你的问题。您的代码还抛出一个IndentationError。请提供答案。我也不能重现这个问题。我不明白为什么在这个例子中你需要Prototype类,如果你对Car类有问题,这是一个Prototype的例子,代码结构,请查看不同的编码结构以获得更多信息。我不知道为什么,我的对象没有打印可读的字符串?