【发布时间】:2017-11-09 07:33:39
【问题描述】:
我正在用 Python3 学习“Learn Python the Hard Way”一书。作者通过这个例子介绍了OOP的概念:
class Song (object):
def __init__(self,lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print (line)
happy_bday = Song(["Happy birthday to you", "I don't want to get sued","So I'll stop right there"])
bulls_on_parade = Song(["They rally around the family","With pockets full of shells"])
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
OOP 对我来说有点有趣。作者建议我们应该对上面的代码进行一点“trash”、“break”和“thrash”。
我试图打印对象“实例化”的变量名称(不确定“实例化”是否是正确的词,也许正确的词是“实例化”)。为了尝试,我在类 Songs() 中添加了以下方法:
class Song (object):
def __init__(self,lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print (line)
def name_of_var(self):
print (Song)
def name_of_var_2(self):
print (object)
def name_of_var_3(self):
print (self)
def name_of_var_3(self):
print (self)
我使用了作者提供的对象示例:
happy_bday = Song(["Happy birthday to you", "I don't want to get sued","So I'll stop right there"])
bulls_on_parade = Song(["They rally around the family","With pockets full of shells"])
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
最后,我尝试做:
print(Song(["They rally around the family","With pockets full of shells"]))
print (happy_bday.name_of_var())
print (happy_bday.name_of_var_2())
print (happy_bday.name_of_var_3())
print (happy_bday.__init__(happy_bday))
我无法实现我的目标。使用上面我得到的方法:
<__main__.Song object at 0x7f4b784f3da0>
<class '__main__.Song'>
None
<class 'object'>
None
<__main__.Song object at 0x7f4b784f3d30>
None
None
pedr
我的目标是创建一些我会做的方法:
print (happy_bday.__some__method())
程序会返回:
happy_bday
也许这在 Python 中是不可能的……如果我没记错的话,你可以在 Lisp/Racket 中做这种事情(但我不是 100% 确定)。这在 Python 中可能吗?我该怎么做?
【问题讨论】:
-
没有简单的方法可以在运行时找出变量的“名称”。无论如何,这不是变量应该的工作方式。但如果你真的需要它:你可以看看
locals()、globals()。 -
如果这本书说你应该这样做,我强烈建议你再找一本书。
-
对象不知道它们被分配到的变量。无论如何,这是你的工作来跟踪它。
-
@ChristianDean,实际上,这本书只是建议我们应该稍微“玩”一下这段代码,以便熟悉 OOP。我对“玩”的态度是一种不寻常和奇怪的方式。这本书没有建议我在上面尝试过什么。
-
所以,为了清楚起见,变量没有实例化。 对象被实例化。变量被分配给。
标签: python python-3.x oop instance-variables