简体   繁体   English

Python:将self传递给类方法或参数

[英]Python: Passing self to class methods or arguments

I am working on a python project with classes that have quite a few parameters and methods. 我正在使用具有很多参数和方法的类在python项目中工作。 In order to reduce complexity, I have been writing the methods as such: 为了降低复杂性,我一直在编写如下方法:

def foo(self):
    return self.parameter1 * self.parameter2

Would it be better practice to explicitly pass the parameters? 显式传递参数是否是更好的做法?

def foo(self, parameter1, parameter2):
    return parameter1 * parameter2

This comes up because I have found it difficult to test the functions in the class without testing the entire class. 之所以这样,是因为我发现在不测试整个类的情况下很难测试该类中的功能。

In order to reduce complexity, I have been writing the methods as such 为了降低复杂度,我一直在写这样的方法

The assumption of this purpose is wrong, self(instance variable) is supposed to be used if you define an instance method. 此目的的假设是错误的,如果您定义实例方法,则应该使用self(实例变量)。

According to pylint: method_could_be_a_function : If a function could be run without self(instance variable), it should be an individual function, not an instance method. 根据pylint:method_could_be_a_function :如果一个函数可以在没有self(实例变量)的情况下运行,那么它应该是一个单独的函数,而不是实例方法。

For example: 例如:

class A(object):

    def __init__(self):
        self.some_instance_var

    def some_instance_method(self):
        #code here is suggested to be related to self(instance variable), eg:
        return self.some_instance_var

This one would be proper to put into class as an instance method. 最好将它作为实例方法放入类中。

class A(object):

    ...

    def foo(self):
        return self.parameter1 * self.parameter2

And this one should be a normal function, not an instance method. 而且这应该是一个普通函数,而不是实例方法。 Because the content of function is not related to self(instance variable). 因为函数的内容与自身(实例变量)无关。

def foo(self, parameter1, parameter2):
    return parameter1 * parameter2

Your question makes some assumptions that are not consistent with OO design. 您的问题做出了一些与OO设计不一致的假设。

If parameter1 and parameter2 are not intrinsic properties of the object represented by self , then they need to be passed. 如果parameter1parameter2 不是 self表示的对象的固有属性,则需要传递它们。 If however, they are intrinsic properties of self , then they should have already been associated with self and do not need to be passed. 但是,如果它们 self固有属性,则它们应该已经与self相关联,不需要传递。

One major point of OO design, and objects in general, is to explicitly associate the data describing the object and the methods to work on the object together. OO设计(通常是对象)的主要要点是将描述对象的数据与在对象上工作的方法明确地关联在一起。

Answer: 回答:

Use a self reference for anything that is intrinsic to the object, and pass as a parameter those values which are not. 对对象内在的任何事物都使用一个self引用,并将那些不是的值作为参数传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM