【发布时间】:2021-09-30 10:01:03
【问题描述】:
我最近一直在尝试使用类方法来更好地理解面向对象的编程。作为示例程序的一部分,我有一个名为circle 的简短类,可用于创建不同的circle 实例。
class circle():
def __init__(self):
self.radius = 10
self.color = 'blue'
def change_color(self, color):
self.color = color
@classmethod
def red_circle(cls):
circle.radius = 10
circle.color = 'red'
return cls
我在类方法中添加了red_circle,这样我就可以为circle 实例设置不同的默认设置。我遇到的问题是,当我使用red_circle 方法时,创建的实例放在mappingproxy() 内?例如:
circle_one = circle()
circle_one.__dict__
给出输出:
{'radius': 10, 'color': 'blue'}
但是使用
circle_two = circle.red_circle()
circle_two.__dict__
给予:
mappingproxy({'__dict__': <attribute '__dict__' of 'circle' objects>,
'__doc__': None,
'__init__': <function __main__.circle.__init__>,
'__module__': '__main__',
'__weakref__': <attribute '__weakref__' of 'circle' objects>,
'change_color': <function __main__.circle.change_color>,
'color': 'orange',
'radius': 10,
'red_circle': <classmethod at 0x7f0e94ab1a10>})
有没有办法可以操纵circle_two 使其看起来与circle_one 实例相同?它目前没有造成任何问题,但最好了解mappingproxy() 的情况。
【问题讨论】:
标签: python class oop methods class-method