Python类中的self代表什么?
在书籍《学习Python 第五版(O'Reilly,Mark Lutz)第912页》中
class PrivateExc(Exception): pass # More on exceptions in Part VII
class Privacy:
def __setattr__(self, attrname, value): # On self.attrname = value
if attrname in self.privates:
raise PrivateExc(attrname, self) # Make, raise user-define except
else:
self.__dict__[attrname] = value # Avoid loops by using dict key
class Test1(Privacy):
privates = ['age']
class Test2(Privacy):
privates = ['name', 'pay']
def __init__(self):
self.__dict__['name'] = 'Tom' # To do better, see Chapter 39!
可能在第五行raise PrivateExc(attrname, self)
有问题,
这里的self参数会被放在第一个位置。
那这一行是不是应该改成raise PrivateExc(self, attrname)
呢?为什么不这样做呢?
3 个回答
当你像这样调用一个方法时:
#!/bin/python
myinstance.some_method(a,b,c)
... 那么这个调用会被传递给 some_method
,变成:some_method(myinstance, a, b, c)
通过这个实例调用的方法,它会作为第一个参数传递给方法。这和 C++ 和 Java 完全不同……那两种语言使用的是隐式的 "this" 引用……这是一种在你方法的作用域内有效的指针,但并不是作为参数传递给你的方法。
我希望这能回答你的问题,不过这个代码示例并没有帮助你更好地理解你想做的事情。
其实这没什么大不了的。
从 Exception
这个类继承而创建自己的异常类,如果没有额外的构造函数,实际上并不会限制你可以传给这个异常类的参数。而且你可以随意选择参数的顺序。
传给 PrivateExc
类的参数会被存储在实例中,作为实例的属性 .args
举个例子:
>>> class MyError(Exception):
... """MyError"""
...
>>> e = MyError("foo", "bar")
>>> e.args
('foo', 'bar')
>>> e
MyError('foo', 'bar')
这本书里说的基本意思是;
如果你想捕获这个异常 PrivateExc
,你可以这样做:
try:
...
except PrivateExc as error:
attrname, obj = error.args
...
我觉得你可能对函数定义和函数调用中的参数有些混淆。
在一个类里,方法(实例方法)在定义时,第一个参数通常是一个非可选参数,通常叫做 self
,像这样:
class Foo:
def foo(self, another_param):
pass
这个 self
代表的是你用来调用 foo
函数的那个实例。如果你有这样的代码:
f=Foo()
f.foo("test")
在上面的代码中,self
代表的是 f
,而 another_param
代表的是 "test"
这个字符串。
然后在 foo
函数里,你可以像使用其他参数一样使用 self
。
假设你有一个 Print
函数,像这样:
def Print(x):
print "Param:", x
那么你可以这样创建你的 Foo
类:
class Foo:
def foo(self, another_param):
Print(another_param) # I think this will not confuse you
或者这样:
class Foo:
def foo(self, another_param):
Print(self) # Now, you may understand this, self is just a param in function calling, like another_param
现在,把 Print
函数改成 PrivateExc
(你可以把它想象成一个用来创建 PrivateExc 实例的函数),你可能也能理解。
希望这些例子能帮助你理解你的问题。