我在思考Python3.6是否有类的默认构造函数。所以我写了一些代码来测试这个问题。但是,当我开始测试时,我留下了比之前更多的疑问。
我试图理解为什么我的程序第11行上的myCat被成功构建,然而我无法解释为什么程序的第27行需要知道它本身。
如果您可以帮忙,请查看此Python代码和输出...它有意义吗? 我创建了两个文件animal.py和an_test_program.py。
我试图理解为什么我的程序第11行上的myCat被成功构建,然而我无法解释为什么程序的第27行需要知道它本身。
如果您可以帮忙,请查看此Python代码和输出...它有意义吗? 我创建了两个文件animal.py和an_test_program.py。
#!/usr/bin/env python3
#animal.py file ==============================
class animal:
name = ""
height = 0
weight = 0
def __init__( self, name, height, weight):
self.name = name
self.height = height
self.weight = weight
def printvars(self):
print(self.name)
print(self.height)
print(self.weight)
#!/usr/bin/env python3
#an_animal_program.py ==============================
import animal as an
#Instantiate a variable of type animal using the special constructor of the class
myDog = an.animal('Capitan', 30, 70)
print('myDog\'s name is ' + myDog.name)
myDog.printvars()
#now play around with Python and discover some things...
#Instantiate a variable of type animal without using the special constructor
myCat = an.animal
print('myCat\'s name is ' + myCat.name)
print('myCat\'s height is ' + "%d" % (myCat.height))
print('myCat\'s weight is ' + "%d" % (myCat.weight))
#notice everything in myCat is empty or zero
#thats because myCat is not initialized with data
#none-the-less myCat is a viable object, otherwise Python would puke out myCat
myCat.name = 'Backstreet'
print('myCat\'s name is ' + myCat.name) # now myCat.name has data in it
#Ouch... this next line produces an error:
#myCat.printvars()
#"an_test_program.py", line 21, in <module>
# myCat.printvars()
#TypeError: printvars() missing 1 required positional argument: 'self'
myCat.printvars(myCat) #ok, I'm rolling with it, but this is wierd !!!
#oh well, enough of the wierdness, see if the myCat var can be
#reinstantiated with an animal class that is correctly constructed
myCat = an.animal('Backstreet', 7, 5)
myCat.printvars()
#I'm trying to understand why myCat constructed ok on line 11
#But I can't explain why line 27 demanded to know itself
#the output is:
# RESTART: an_test_program.py
#myDog's name is Capitan
#Capitan
#30
#70
#myCat's name is
#myCat's height is 0
#myCat's weight is 0
#myCat's name is Backstreet
#Backstreet
#0
#0
#Backstreet
#7
#5
.__init__
是实例的初始化器。实例构造函数被称为.__new__
。类从object
继承.__new__
方法,通常无需覆盖它,但这是可以做到的。 - PM 2Ring