Skip to content

Commit ec18fcb

Browse files
committed
add class
1 parent 8105eb3 commit ec18fcb

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

class.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#!/usr/bin/python
2+
#coding:utf-8
3+
4+
# 如果一个 Python 函数,类方法,或属性的名字
5+
# 以两个下划线开始 (但不是结束),它是私有的;
6+
# 其它所有的都是公有的。
7+
# Python 没有类方法保护 的概念 (只能用于它们自已的类和子类中)。
8+
# 类方法或者是私有 (只能在它们自已的类中使用) 或者是公有 (任何地方都可使用)。
9+
10+
# 虽然ptyhon 不支持方法的重载,但,其实没必要 见 http://www.zhihu.com/question/20053359
11+
# 以及python作者搞的重载 http://www.artima.com/weblogs/viewpost.jsp?thread=101605
12+
class Animal:
13+
"""Animal的文档的描述字符串"""
14+
typeName = 'animal'; # 静态方法
15+
def __init__(self, name = 'unknow', say='呜呜呜'):#构造函数
16+
self.name = name; # self相当于this,实例对象只能在self上定义
17+
self.say = say;
18+
def describe(self): # 实例方法
19+
return self.say + '~ My name is ' + self.name + '. I\'m a ' + Animal.typeName;
20+
def __secret(self): # 私有变量,不会被继承
21+
print 'haha you find me!';
22+
@staticmethod # 2.4 后的版本需要加这个
23+
def haha(): # 类方法 第一个参数不能加 self。因为其不能访问self
24+
print Animal.typeName + ' haha';
25+
26+
an = Animal('Nacy'); #创建实例不能带 new,否则报错!
27+
an.haha(); # 也可以调用
28+
Animal.haha();
29+
print an.describe();
30+
an._Animal__secret();# 访问私有变量
31+
print Animal.typeName, an.name, an.typeName;# animal Nacy animal
32+
an.typeName = 'change';
33+
print Animal.typeName, an.typeName;# animal, change
34+
35+
# python 支持多继承
36+
class Cat(Animal): # 继承,python不会主动的调父类的构造函数
37+
"""docstring for Cat"""
38+
def __init__(self, name):
39+
Animal.__init__(self, name, '喵喵喵喵');
40+
41+
cat = Cat('Xiao hua');
42+
print cat.describe();
43+
44+

0 commit comments

Comments
 (0)