Class 和对象错误;语法错误

Class and Object error; incorrect syntax

我怎样才能打印每件产品?即 "I am a iPad, an Apple Product"

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()

这里的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类中的一个基本事实。 class的任何一个方法都至少接受一个参数,如果方法有多个参数,则该参数为第一个参数,即调用该函数的对象。

您似乎希望每个实例都有自己的名称,您可以打印出来。像这样的东西(我把你的 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()
    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()

这将创建 class Apple 的 3 个实例,即 iPad、iWatch 和 iMac。一旦这 3 个实例为 created/instantiated,就会调用 init() 方法。在实例化每个对象的行中传递的字符串是将为每个对象存储在 self.name 中的名称。 'Self' 只是对象名称的占位符。