Python 什么';这种上课方法有什么问题?
为什么这样不行?我试图在课堂上访问我的名字,并说你好,我的名字是[myname][yourname]使用Python 什么';这种上课方法有什么问题?,python,class,Python,Class,为什么这样不行?我试图在课堂上访问我的名字,并说你好,我的名字是[myname][yourname]使用self.name而不是name: class Person: def __init__(self, name): self.name = name def greet(name, other_name): return "Hi {0}, my name is {1}".format(other_name, name) 有两种可能性: 1) 如果希望greet()方
self.name
而不是name
:
class Person:
def __init__(self, name):
self.name = name
def greet(name, other_name):
return "Hi {0}, my name is {1}".format(other_name, name)
有两种可能性: 1) 如果希望
greet()
方法成为实例方法,则缺少self
参数:
def greet(other_name):
return "Hi {0}, my name is {1}".format(other_name, self.name)
然后您可以这样调用它:
def greet(self, other_name):
return "Hi {0}, my name is {1}".format(other_name, self.name),
@staticmethod
def greet(name, other_name):
return "Hi {0}, my name is {1}".format(other_name, name)
2) 您希望它是一个静态方法:
adam = Person("Adam")
adam.greet("John")
然后您可以这样调用它:
def greet(self, other_name):
return "Hi {0}, my name is {1}".format(other_name, self.name),
@staticmethod
def greet(name, other_name):
return "Hi {0}, my name is {1}".format(other_name, name)
您需要将
self
传递给该方法
所以
您的实际问题是您正在将实例方法
greet
定义为:
def greet(self, name, other_name):
return "Hi {0}, my name is {1}".format(other_name, name)
Python中的实例方法将实例
作为方法定义中的第一个参数。您现在在这里所做的是调用该实例name
。但是,在类的\uuu init\uu
中,您使用self
引用实例对象。这就是你的主要问题所在
因此,当您实际尝试调用方法时,您很可能会得到如下结果:
def greet(name, other_name):
然后,需要引用实例属性引用实例并从该对象访问属性:
因此,要在greet
方法中访问name
,它必须是self.name
因此:
为了更好地理解所有这些,您应该阅读更多关于类在Python中如何工作的内容。以下是关于它的教程部分:
到底什么不起作用?为我们提供一个示例usageAsking Why not这项工作对读者帮助不大。你需要解释什么不起作用。你所期望的会发生,那不是。这很奇怪。当
init
中定义了self.name
,然后将其作为参数传递给greet
方法时,为什么这是公认的解决方案。这没有多大意义。
def greet(self, other_name):
"Hi {0}, my name is {1}".format(other_name, self.name)