我如何打印每件产品?即,"我是iPad,Apple产品"
class Apple:
def method1(self):
print "I am a %s , an Apple Product" % self
iPad = Apple()
print ipad.method1()
iWatch = Apple()
print iwatch.method1()
iMac = Apple()
print iMac.method1()
答案 0 :(得分:0)
此处的self参数表示调用该函数的对象。为了您的目的,请使用:
class Apple:
def method1(self,name):
print "I am a %s , an Apple Product" %(name)
iWatch = Apple()
iWatch.method1("iPod")
或者另一种方法是:
class Apple:
def __init__(self,name):
self.name = name
def method1(self):
print "I am a %s , an Apple Product" %(self.name)
iWatch = Apple("iPod")
iWatch.method1()
现在,这将有效。
这实际上是Python类中的基本事实。类的任何方法都至少接受一个参数,如果方法有多个参数,它将是第一个参数,该参数是调用函数的对象。
答案 1 :(得分:0)
您似乎希望每个实例都有自己可以打印的名称。这样的事情(我已经命名为method1
" describe
"):
class Apple(object):
def __init__(self, name):
self.name = name
def describe(self):
return "I am an %s, an Apple Product" % self.name
iPad = Apple("iPad")
print iPad.describe()
iWatch = Apple("iWatch")
print iWatch.describe()
iMac = Apple("iMac")
print iMac.desc()
答案 2 :(得分:0)
class Apple(object):
def __init__(self, name):
self.name = name
def method1(self):
print "I am a %s , an Apple product." % self.name
iPad = Apple('Ipad')
iPad.method1()
iMac = Apple('iMac')
iMac.method1()
iWatch = Apple('iWatch')
iWatch.method1()
这将创建Apple类的3个实例,即iPad,iWatch和iMac。一旦创建/实例化这3个实例,就会调用 init ()方法。传入的字符串然后是每个对象实例化的行,是将存储在每个对象的self.name中的名称。 '自'只是对象名称的占位符。