|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
1.self 是一种绑定方法。
本人萌新一枚,self详细讲解请参考http://python.jobbole.com/81921/
2.魔法方法之一:"__init__"(左右两条下滑线),也是一种构造方法,在创建实例对象是会自动调用。
- >>> class Ball:
- def __init__(self,name):
- self.name = name
- def getName(self):
- print('I am %s '%self.name)
-
- >>> a =[color=Red] Ball('球A')[/color]
- >>> a.getName()
- I am 球A
- >>> b = [color=Red]Ball()[/color]
- Traceback (most recent call last):
- File "<pyshell#28>", line 1, in <module>
- b = Ball()
- TypeError: __init__() missing 1 required positional argument: 'name'
复制代码
3.python中用"__+变量名"(双下划线)的形式隐藏变量
- >>> class Person():
- __name = '小甲鱼'
- def getName(self):
- return self.__name
-
- >>> p = Person()
- [color=Red]#如下,无法访问__name[/color]
- >>> p.__name
- Traceback (most recent call last):
- File "<pyshell#6>", line 1, in <module>
- p.__name
- AttributeError: 'Person' object has no attribute '__name'
- [color=Red]#通过类对象中的函数访问[/color]
- >>> p.getName()
- '小甲鱼'
- [color=Red]#通过"_类名__变量名"的方法访问[/color]
- >>> p._Person__name
- '小甲鱼'
复制代码 |
评分
-
查看全部评分
|