自我,没有自我和cls

还有一个问题是关于“自我”是什么,如果你不使用“自我”和什么是“自我”,会发生什么。 我“已经完成了我的功课”,我只是想确保我完成了所有工作。

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

cls - 每个实例创建它自己的属性“复制”,所以如果你想要一个类的所有实例共享同一个变量,你可以在类声明中用' cls '作为变量名的前缀。

这样好吗? 谢谢。


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

不在对象/类中,只在类的实例方法中。 self只是一种惯例,你可以将它称为任何你想要的,甚至每种方法都有不同的东西。

因此,如果您没有在类方法中使用自变量前缀变量,则无法在类的其他方法或类之外访问该变量。

self用于实例方法中, cls通常用于类方法中。 否则,正确。

因此,如果您只想将该变量局部用于该方法,则可以忽略它。

是的,在一个方法中,变量名就像其他任何函数一样 - 解释器在本地查找名称,然后在关闭中查找,然后在全局变量/模块级别中查找,然后在Python内置函数中查找。

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

不,你不能只从方法参数中省略“自我”。 你必须告诉Python你想要一个staticmethod ,它不会自动传递类的实例,通过在def行之上执行@staticmethod ,或者在方法体之下执行mymethod = staticmethod(mymethod)

每个实例都创建它自己的属性“复制”,所以如果你想要一个类的所有实例共享同一个变量,你可以在类声明中用'cls'作为变量名的前缀。

在类定义内部,但在任何方法之外,名称都绑定到类 - 这就是您如何定义方法等。您不要在它们cls或其他任何东西。

cls通常用于__new__特殊staticmethodclassmethod s中,这与staticmethod类似。 这些方法只需要访问类,而不是特定于每个类的实例。

classmethod里面,是的,你会用这个来指代你想要的类的所有实例和类本身的属性,以便共享。

self一样, cls只是一个惯例,你可以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

在实例通过此参数自动传递的常规方法中,您使用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

输出:

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

>>> Test.greet()
class <class '__main__.Test'> greet you
链接地址: http://www.djcxy.com/p/54731.html

上一篇: self, no self and cls

下一篇: Why accessing to class variable from within the class needs "self." in Python?