1 python oop instance-variables python-3.x
我正在学习使用Python3"用Python学习Python"这本书.作者用这个例子介绍了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()
Run Code Online (Sandbox Code Playgroud)
OOP对我来说很有趣.作者建议我们应该将代码"垃圾","破解"和"捶打"一下.
我试图打印对象是"实例化"的变量名称(不确定"instanced"是否是正确的单词,也许正确的单词是"实例化").为了尝试这一点,我在类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)
Run Code Online (Sandbox Code Playgroud)
我使用了作者提供的对象示例:
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()
Run Code Online (Sandbox Code Playgroud)
最后,我试着做:
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))
Run Code Online (Sandbox Code Playgroud)
我无法达到目标.使用上面的方法我得到:
<__main__.Song object at 0x7f4b784f3da0>
<class '__main__.Song'>
None
<class 'object'>
None
<__main__.Song object at 0x7f4b784f3d30>
None
None
pedr
Run Code Online (Sandbox Code Playgroud)
我的目标是创建一些我会做的方法:
print (happy_bday.__some__method())
Run Code Online (Sandbox Code Playgroud)
该计划将返回:
happy_bday
Run Code Online (Sandbox Code Playgroud)
也许在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"])
Run Code Online (Sandbox Code Playgroud)
这会创建一个Song对象,它位于计算机内存区域"堆"上.它还会创建一个名为的变量happy_bday,它引用您刚刚创建的Song对象.但是Song对象本身并不知道这一点.
事实上,如果你跑
happy_bday2 = happy_bday
Run Code Online (Sandbox Code Playgroud)
你将创建另一个变量,happy_bday2它引用完全相同的Song对象.事实上,如果你现在要运行该线路
happy_bday.lyrics[0] = "Happy Birthday To You"
Run Code Online (Sandbox Code Playgroud)
添加一些大写,歌词happy_bday2也会改变.那是因为即使你有两个独立的变量,它们实际上只是两种引用内存中完全相同的对象的方式.
希望现在很清楚为什么你不能问Song对象是什么变量引用它; 可能有多个引用它的变量,或根本没有变量(毕竟,你可以写Song(["some lyrics"]).var_name(),在这种情况下,应该打印什么?).
如果你想想象一下这里有一个很棒的工具叫PythonTutor:http://pythontutor.com .您可以输入代码,并查看正在创建的变量和对象.
| 归档时间: |
|
| 查看次数: |
218 次 |
| 最近记录: |