Python参数包含自己类的对象

2024-10-04 11:33:57 发布

您现在位置:Python中文网/ 问答频道 /正文

为了尝试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中不包含这样的对象


Tags: intestforobjectisdefanotherarg
3条回答

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中,但是,它将与dictionaryParams中的paramone匹配

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>

在python中存在你提到的“self”对象。。self对象有点像java中的“this”,但有一些不同

在dictionaryParams函数中,paramone充当self对象,因为您没有将它声明为@staticmethod

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

相关问题 更多 >