还有一个关于“自我”是什么的问题,如果你不使用“自我”和“cls”是为了什么,会发生什么。我“做了我的家庭作业”,我只是想确保我得到了一切。
self -要访问对象的属性,需要在属性名称前加上对象名称(objname.attributename)。self用于访问对象(类)本身内的属性的方式也是一样的。因此,如果没有在类方法中用self作为变量的前缀,那么您就无法在类的其他方法中或类之外访问该变量。因此,如果您想使变量只位于该方法的局部变量中,可以省略它。同样,如果您有一个方法,并且您没有任何想要与其他方法共享的变量,您可以从方法参数中省略self。
cls --每个实例都会创建自己的属性“副本”,因此,如果希望类的所有实例共享相同的变量,可以在类声明中在变量名前加上'cls‘。
这样可以吗?谢谢。
发布于 2011-09-26 12:14:54
与self用于访问对象(类)本身内的属性的方式相同。
不是在对象/类内部,而是在类的实例方法中。self只是一种约定,您可以随意称呼它,甚至在每种方法中都有不同的名称。
因此,如果您没有在类方法中以self作为前缀,那么您将无法在类的其他方法中或类之外访问该变量。
实例方法中使用self,类方法中经常使用cls。否则,是正确的。
如果希望使变量仅限于该方法,则可以省略
。
是的,在方法中,变量名就像在任何其他函数中一样--解释器在本地查找名称,然后在闭包中查找,然后在全局/模块级别,然后在Python内置中查找。
同样,如果您有一个方法,并且您没有任何想要与其他方法共享的变量,您可以从方法参数中省略self。
不,不能从方法参数中忽略"self“。您必须告诉Python您需要一个staticmethod,它不会通过在def行上执行@staticmethod或在方法主体下面执行mymethod = staticmethod(mymethod)来自动传递类的实例。
每个实例都会创建自己的属性“副本”,因此,如果您希望类的所有实例共享相同的变量,您可以在类声明中以'cls‘作为变量名的前缀。
在类定义中,但是在任何方法之外,名称都绑定到类中--这就是定义方法等的方法。
cls通常用于__new__特殊的staticmethod或classmethod,这与staticmethod类似。这些方法只需要访问类,而不需要特定于类的每个实例。
在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发布于 2011-09-26 12:01:47
在常规方法中使用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 youhttps://stackoverflow.com/questions/7554738
复制相似问题