【发布时间】:2015-11-11 23:13:49
【问题描述】:
假设我有以下代码:
lens_A = Lens(...) # declare an object of type 'Lens' called 'lens_A'
table = Bench() # declare an object 'Bench' called 'table'
table.addcomponent(lens_A, 10)
addcomponent(self, component, position): # a method inside the class Bench
self.__component_class.append(component)
self.__component_position.append(position)
self.__component_name.append(...) # how to do this????
我想写最后一行,这样我就可以将类变量('lensA')的名称添加到列表self.__component_name,但不能添加实例的位置(在self.__component_class 中完成)。该怎么做?
【问题讨论】:
-
您为什么要这样做?相反,您可以将 name 属性作为
Lens类的一部分并引用它。 -
对象本质上没有名称。如果你这样做
table.addcomponent(Lens(...), 10)会发生什么? -
如果你说
lens_A = lens_B = Lens(),哪个名字是对的。 -
所以除了向类添加额外的属性之外,没有其他方法可以获取我为方法的参数“组件”键入的“单词”(即“lensA”)?
-
没错。事实上,对于大多数编程语言来说,在执行时可以观察到事物名称的情况是例外的。一般规则通常是(当根据语言的绑定语义完成时)名称更改不会改变程序的行为。
标签: python string class oop instance