雕刻时光

just do it……nothing impossible
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

python的面向对象

Posted on 2013-11-30 20:52  huhuuu  阅读(249)  评论(0编辑  收藏  举报

 

1.self

类的方法与普通的函数只有一个特别的区别——它们必须有一个额外的第一个参数名称,但是在调用这个方法的时候你不为这个参数赋值,Python会提供这个值。这个特别的变量指对象本身,按照惯例它的名称是self。

你一定很奇怪Python如何给self赋值以及为何你不需要给它赋值。举一个例子会使此变得清晰。假如你有一个类称为MyClass和这个类的一个实例MyObject。当你调用这个对象的方法MyObject.method(arg1, arg2)的时候,这会由Python自动转为MyClass.method(MyObject, arg1, arg2)——这就是self的原理了。

观察如下代码:

class data:
    a=1
    b=2
    c=3
    def change2(self):
        a=9
        b=8
        c=10
    
temp=data()
print temp.a,temp.b,temp.c
temp.change2()
print temp.a,temp.b,temp.c

猜测会是什么结果,如果是第一次的话,会惊讶到吧= = (猜测change2函数体内的a,b,c是局部变量)

class data:
    a=1
    b=2
    c=3
    def change2(self):
        self.a=9
        self.b=8
        self.c=10
    def sayHi(self):
        print("Hello, how are you?")
    
temp=data()
print temp.a,temp.b,temp.c
temp.change2()
print temp.a,temp.b,temp.c
temp.sayHi()

self就是特指这个变量本身

2.全部变量的使用

在函数也要写上全局变量的标识符

global x
x =123
def fun():
    #global x
    x=12345678
    print dir()
print dir()
print x
fun()
print x

打印出:

['__builtins__', '__doc__', '__name__', '__package__', 'fun', 'x']
123
['x']
123

 说明X是在函数体里的全局变量

global x
x =123
def fun():
    global x
    x=12345678
    print dir()
print dir()
print x
fun()
print x

['__builtins__', '__doc__', '__name__', '__package__', 'fun', 'x']
123
[]
12345678

函数体内变量没有,这样就知道X是全局变量了

3. 通过dir() 可以方便的知道现在的作用域下的对象有什么