Python - 自我,没有自我和cls

Joe*_*lmc 52 python class object self

还有一个关于"自我"是什么的问题,如果你不使用'自我'和什么是'cls'会发生什么.我"完成了我的作业",我只是想确保自己完成所有工作.

self- 要访问对象的属性,需要在属性名称前加上对象名称(objname.attributename).同样的方法self用于访问对象(类)本身的属性.因此,如果您没有在类方法中使用self作为self的前缀,那么您将无法在类的其他方法中或在类之外访问该变量.因此,如果您只想将变量局部化为该方法,则可以省略它.同样的方法如果你有一个方法并且你没有想要与其他方法共享的任何变量,你可以省略self方法参数.

cls- 每个实例都创建它自己的属性"副本",因此如果您希望类的所有实例共享同一个变量,您可以cls在类声明中使用' '作为前缀.

这样可以吗?谢谢.

agf*_*agf 91

self用于访问对象(类)本身内部的属性.

不在对象/类中,只是在类的实例方法中.self只是一个惯例,你可以随意调用它,即使每种方法都有不同的东西.

因此,如果您没有在类方法中使用self作为self的前缀,那么您将无法在类的其他方法中或在类之外访问该变量.

self实例方法中使用,cls通常用在类方法中.否则,正确.

因此,如果您只想将变量局部化为该方法,则可以省略它.

是的,在一个方法中,变量名称就像在任何其他函数中一样 - 解释器在本地查找名称,然后在闭包中查找,然后在globals/module级别,然后在Python内置函数中查找.

同样的方法如果你有一个方法并且你没有想要与其他方法共享的任何变量,你可以省略方法参数中的self.

不,你不能只从方法参数中省略"self".你必须告诉Python你想要一个staticmethod,它不会自动传递给类的实例,通过在行@staticmethod上方defmymethod = staticmethod(mymethod)在方法体下面传递.

每个实例都创建它自己的属性"副本",因此如果您希望类的所有实例共享同一个变量,您可以在类声明中使用"cls"作为变量名称的前缀.

类定义中,但在任何方法之外,名称都绑定到类 - 这就是你如何定义方法等.你不用它们cls或其他任何东西作为前缀.

cls通常用于__new__特殊staticmethodclassmethods中,与staticmethods 类似.这些方法只需要访问类,但不能访问特定于每个类实例的内容.

在a classmethod,是的,您可以使用它来引用您希望所有类实例和类本身共享的属性.

就像self,cls只是一个惯例,你可以随意调用它.

一个简短的例子:

class Foo(object):

    # you couldn't use self. or cls. out here, they wouldn't mean anything

    # this is a class attribute
    thing = 'athing'

    def __init__(self, bar):
        # I want other methods called on this instance of Foo
        # to have access to bar, so I create an attribute of self
        # pointing to it
        self.bar = bar

    @staticmethod
    def default_foo():
        # static methods are often used as alternate constructors,
        # since they don't need access to any part of the class
        # if the method doesn't have anything at all to do with the class
        # just use a module level function
        return Foo('baz')

    @classmethod
    def two_things(cls):
        # can access class attributes, like thing
        # but not instance attributes, like bar
        print cls.thing, cls.thing
Run Code Online (Sandbox Code Playgroud)

  • 如果你真的想要理解这类东西,并且你已经完成了一两个Python教程,并阅读了关于`classmethod`,`staticmethod`等的文档,那么请阅读[Python数据模型](http ://docs.python.org/reference/datamodel.html)参考页面. (3认同)

Thi*_*ter 11

self在常规方法中使用第一个参数,其中实例通过此参数自动传递.因此无论第一个参数在方法中是什么 - 它指向当前实例

使用@classmethod它来装饰方法时,将类作为第一个参数传递,因此最常见的名称是cls指向.

你通常不添加任何变量前缀(匈牙利表示法是坏的).


这是一个例子:

class Test(object):
    def hello(self):
        print 'instance %r says hello' % self
    @classmethod
    def greet(cls):
        print 'class %r greet you' % cls
Run Code Online (Sandbox Code Playgroud)

输出:

>>> Test().hello()
instance <__main__.Test object at 0x1f19650> says hello

>>> Test.greet()
class <class '__main__.Test'> greet you
Run Code Online (Sandbox Code Playgroud)

  • 匈牙利的表示法也不错.这是恶魔. (4认同)
  • 我想我会养成低估答案的习惯,这些答案会产生绝对和未经证实的主张.匈牙利表示法有两种类型; 在这里阅读更多内容:http://www.joelonsoftware.com/articles/Wrong.html (4认同)