为了尝试Python,我创建了以下类:
class FunctionParameters(object):
def __init__(self):
print 'initialized a functionParameters object'
#if this method is not static an object (self?) is passed to arguments
#@staticmethod
def argumentParams(*arguments):
print 'argumentParams ---'
for item in arguments:
print 'arg ' + str(item)
print
#no such object is passed to this method
def dictionaryparams(paramone,*arguments, **keywords):
print 'dicitonaryparams ---'
for item in arguments:
print item
print 'I can get more than two params because i use **paramname'
for item in keywords:
print item
在main.py中,我用以下方法测试这个类:
import FunctionParameters
paramsTest = FunctionParameters.FunctionParameters()
paramsTest.argumentParams("before", "test", "some arg", "another arg")
paramsTest.dictionaryparams("test" ,"some arg", "another arg", test="some" , bert = "henk")
运行main时,我注意到argumentParams的输出是:
argumentParams ---
arg <FunctionParameters.FunctionParameters object at 0x02D76230>
arg before
arg test
arg some arg
arg another arg
对于字典参数
dicitonaryparams ---
test
some arg
another arg
I can get more than two params because i use **paramname
test
bert
注意参数的第一行。但是,当对argumentParams使用@staticmethod时,结果不包含该行。在我发现这一点之后,我试图看看如果我使dictionaryparams函数是静态的,是否有什么区别,但是对于该函数,它不传递对象(比如第一行argumentParams)静态的
那么为什么这两个函数中的参数有区别呢?为什么argumentParams(*arguments)包含
FunctionParameters.FunctionParameters object
为什么dictionaryparams(paramone,*arguments,**keywords)在arguments param中不包含这样的对象
self
参数始终作为第一个参数传递给方法。所以,你打的两个电话都会变成这样:现在,
paramTest
将被捕获在argumentParams
*arguments
中,但是,它将与dictionaryParams
中的paramone
匹配dictionaryparams
确实包含一个这样的参数对象:'paramone'
,您没有输出它。例如,调用方法的实例方法(非静态、非类方法)将自动作为第一个位置参数传递:这些调用相当于:
在python中存在你提到的“self”对象。。self对象有点像java中的“this”,但有一些不同
在dictionaryParams函数中,paramone充当self对象,因为您没有将它声明为
@staticmethod
我真的建议this video更好地理解它和this one
相关问题 更多 >
编程相关推荐