Python - self, no self and cls
还有一个关于"自我"的问题,如果你不使用"自我"会发生什么,以及"cls"是什么。我"已经完成了我的家庭作业",我只想确保我把它都做好。
这样可以吗?谢谢。
The same way self is used to access an attribute inside the object (class) itself.
号
不在对象/类内,只在类的实例方法内。
So if you didn't prefix a variable with self in a class method, you wouldn't be able to access that variable in other methods of the class, or outside of the class.
号
实例方法中使用
So you could omit it if you wanted to make the variable local to that method only.
号
是的,在一个方法中,变量名与其他任何函数中的变量名一样——解释器在本地查找该名称,然后在闭包中查找,然后在全局/模块级别查找,最后在python内置模块中查找。
The same way if you had a method and you didn't have any variable you wanted to share with other methods, you could omit the self from the method arguments.
号
不,不能从方法参数中省略"self"。你必须告诉python你想要一个
Each instance creates it's own"copy" of the attributes, so if you wanted all the instances of a class to share the same variable, you would prefix that variable name with 'cls' in the class declaration.
号
在类定义的内部,但在任何方法的外部,名称都绑定到类——这就是定义方法等的方式。您不会在它们前面加上
在
和
一个简单的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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 |
在常规方法中,使用
当用
通常不给任何变量加前缀(匈牙利符号不好)。
下面是一个例子:
1 2 3 4 5 6 | class Test(object): def hello(self): print 'instance %r says hello' % self @classmethod def greet(cls): print 'class %r greet you' % cls |
输出:
1 2 3 4 5 | >>> Test().hello() instance <__main__.Test object at 0x1f19650> says hello >>> Test.greet() class <class '__main__.Test'> greet you |
号