人若有情死得早 发表于 2017-7-13 21:04:59

037类和对象:面向对象编程

OOA:面向对象分析
OOD:面向对象设计
OOP:面向对象编程
1.self是什么?怎么使用?
>>> class Ball:
        def setName(self, name):
                self.name = name
        def kick(self):
                print("我叫%s,该死的,谁踢我..." %self.name)

               
>>> a = Ball()
>>> a.setName('球A')
>>> b = Ball()
>>> b.setName('球B')
>>> c = Ball()
>>> c.setName('土豆')
>>> a.kick()
我叫球A,该死的,谁踢我...
>>> c.kick()
我叫土豆,该死的,谁踢我...
2.Python的魔法方法 __init__(self)
据说,Python的对象天生拥有一些神奇的方法,他们是面向对象的Python的一切......
他们是可以给你的类增加魔力的特殊方法......
如果你的对象实现了这些方法中的某一个,那么这个方法就会在特殊的情况下被Python所调用,而这一切都是自动发生的......
__init__(self) 构造方法
__init__(self, param1, param2...)
>>> class Ball:
        def __init__(self, name):
                self.name = name
        def kick(self):
                print("我叫%s,该死的,谁踢我..." %self.name)

               
>>> b = Ball('土豆')
>>> b.kick()
我叫土豆,该死的,谁踢我...
>>> c = Ball()
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
    c = Ball()
TypeError: __init__() missing 1 required positional argument: 'name'
3.公有和私有
name mangling 名字改编,名字重整
在Python中定义私有变量只需要在变量名或函数名前加上“__”两个下划线,那么这个函数或变量就会为私有的了。
>>> class Person:
        name = "小甲鱼"

       
>>> p = Person()
>>> p.name
'小甲鱼'
>>> class Person:
        __name = "小甲鱼"

       
>>> p = Person()
>>> p.__name
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
    p.__name
AttributeError: 'Person' object has no attribute '__name'
>>> p.name
Traceback (most recent call last):
File "<pyshell#33>", line 1, in <module>
    p.name
AttributeError: 'Person' object has no attribute 'name'
>>> p = Person()
>>> p.__name
Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
    p.__name
AttributeError: 'Person' object has no attribute '__name'
>>> p.getName()
'小甲鱼'
访问类型:_类名__变量名
>>> p._Person__name
'小甲鱼'
页: [1]
查看完整版本: 037类和对象:面向对象编程