Python参数包含自己的类

时间:2017-11-01 13:12:34

标签: python python-2.7

要尝试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

和dictionaryparams

dicitonaryparams ---
test
some arg
another arg
I can get more than two params because i use **paramname
test
bert

请注意 argumentParams 的第一行。但是,当使用@staticmethod作为argumentParams时,结果不包含该行。在我发现这个之后,我试着看看是否有任何区别,如果我将 dictionaryparams 函数设为静态但是对于该函数它不会传递对象(如argumentParams的第一行)静态与否。

那么为什么这两个函数中的参数之间存在差异?为什么 argumentParams(* arguments)包含

  

FunctionParameters.FunctionParameters对象

为什么 dictionaryparams(paramone,* arguments,** keywords)在参数param中不包含这样的对象?

3 个答案:

答案 0 :(得分:3)

dictionaryparams确实包含一个您未输出的参数对象: 'paramone' 。例如,方法(非静态,非类方法),调用该方法的实例将自动作为第一个位置参数传递:

class A(object):
    def a(a1, *args):
        print(a1)  # this s the usual 'self' reference
    def b(*args):
        print(args[0])  # here the first of args is the 'self' reference


x = A()

x.a()
<__main__.A object at 0x00000267AB0C96A0>

x.b()
<__main__.A object at 0x00000267AB0C96A0>

这些电话相当于:

A.a(x)  # x -> a1
<__main__.A object at 0x00000267AB0C96A0>

A.b(x)  # x -> args[0]
<__main__.A object at 0x00000267AB0C96A0>

答案 1 :(得分:0)

self参数始终作为方法的第一个参数传递。因此,您所做的两个电话都将更改为以下内容:

paramsTest.argumentParams(paramTest, "before", "test", "some arg", "another arg")
paramsTest.dictionaryparams(paramTest, "test" ,"some arg", "another arg", test="some" , bert = "henk")

现在,paramTest将在argumentParams *arguments内被捕获,但它将与paramone中的dictionaryParams匹配。

答案 2 :(得分:0)

在python中存在&#34; self&#34;你提到的对象..自我对象有点像&#34;这&#34;在java中但有一些差异

在你的dictionaryParams函数中,paramone充当自我对象,因为你没有将它声明为@staticmethod

我真的建议this video更好地理解它并this one