Skip to main content
 首页 » 编程设计

python之如何在 Python OOP 中打印 "instantiated"变量

2025年05月04日15tuyile006

我正在用 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 对我来说有点有趣。作者建议我们应该对上面的代码进行一些“破坏”、“破坏”和“破坏”。

我试图打印对象在其中被“实例化”的变量名称(不确定“实例化”在这里是否是正确的词,也许正确的词是“实例化”)。为了尝试这一点,我在 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 中可能吗?我该怎么做?

请您参考如下方法:

让您感到困惑的是,对象实际上并没有名称!假设我们使用 Song 构造函数创建了一首 Song,并将其放入名为 happy_bday 的变量中:

happy_bday = Song(["Happy birthday to you", "I don't want to get sued","So I'll stop right there"]) 

这会创建一个 Song 对象,它位于“堆”上,这是您计算机中的一个内存区域。它还会创建一个名为 happy_bday 的变量,引用您刚刚创建的 Song 对象。不过,Song 对象本身并不知道这一点。

事实上,如果你跑

happy_bday2 = happy_bday 

您将创建另一个变量 happy_bday2,它引用完全相同的 Song 对象。事实上,如果你现在运行这条线

happy_bday.lyrics[0] = "Happy Birthday To You" 

要添加一些大写字母,happy_bday2 的歌词也会更改。这是因为即使您有两个独立的变量,它们实际上也只是引用内存中完全相同对象的两种方式。

希望现在您能清楚为什么不能询问 Song 对象引用它的变量是什么;可能有多个变量引用它,或者根本没有变量(毕竟,你可以只写 Song(["some lyrics"]).var_name(),在这种情况下,应该打印出来?)。

如果您想将其可视化,这里有一个名为 PythonTutor 的好工具:http://pythontutor.com .您可以输入您的代码,并查看正在创建的变量和对象。