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)
为什么这不起作用?我想在课堂上访问我的名字,并说我的名字是[myname] [yourname]
答案 0 :(得分:2)
您的实际问题是您将实例方法greet
定义为:
def greet(name, other_name):
Python中的实例方法将instance
作为方法定义中的第一个参数。你现在在这里做的是调用该实例name
。但是,在您的班级__init__
中,您使用self
来引用您的实例对象。这是你的主要问题出现的地方。
所以,当你真正尝试调用你的方法时,你最有可能得到这样的东西:
Hi bob, my name is <__main__.Person object at 0x1018ff2b0>
因此,您实际上正在打印Person
类的实例对象。再次,您将此命名为name
。就像打印self
一样。
这里需要纠正两件事。首先,您需要正确定义实例greet
方法,以保持实例对象名称一致。
def greet(self, other_name):
然后,您需要引用引用您的实例的实例属性并从该对象访问属性:
因此,您希望在name
方法中访问greet
,它必须为self.name
。
所以:
"Hi {0}, my name is {1}".format(other_name, self.name)
为了更好地掌握所有这些,你应该阅读更多关于类如何在Python中工作的内容。这是关于它的教程部分:
答案 1 :(得分:0)
使用self.name
代替name
:
def greet(other_name):
return "Hi {0}, my name is {1}".format(other_name, self.name)
答案 2 :(得分:0)
有两种可能性:
1)您希望1. Add one "Lookup" component and pass output of "Excel source" to it.
2. Edit "Lookup" component, and add second source of input to it from your existing table (where you have work email).
3. Join these two inputs to "Lookup" component on the basis of one of the key columns,
so that in output you have two columns one email column from source and one email column from destination.
3. Add "Derived column" component and pass output of "Lookup" to it.
4. Edit "Derived Column", add new column and add expression to check whether email column has "@work-domain" or not.
If yes, then source email else destination email.
方法成为实例方法,然后缺少greet()
参数:
self
然后你可以像这样调用它:
def greet(self, other_name):
return "Hi {0}, my name is {1}".format(other_name, self.name),
2)你希望它是一个静态的方法:
adam = Person("Adam")
adam.greet("John")
然后你可以像这样调用它:
@staticmethod
def greet(name, other_name):
return "Hi {0}, my name is {1}".format(other_name, name)
答案 3 :(得分:0)
您需要将 def greet(self, name, other_name):
return "Hi {0}, my name is {1}".format(other_name, name)
传递给方法
Why do you need explicitly have the "self" argument into a Python method?
所以
PartialView