Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitec18fcb

Browse files
committed
add class
1 parent8105eb3 commitec18fcb

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+
classAnimal:
13+
"""Animal的文档的描述字符串"""
14+
typeName='animal';# 静态方法
15+
def__init__(self,name='unknow',say='呜呜呜'):#构造函数
16+
self.name=name;# self相当于this,实例对象只能在self上定义
17+
self.say=say;
18+
defdescribe(self):# 实例方法
19+
returnself.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+
defhaha():# 类方法 第一个参数不能加 self。因为其不能访问self
24+
printAnimal.typeName+' haha';
25+
26+
an=Animal('Nacy');#创建实例不能带 new,否则报错!
27+
an.haha();# 也可以调用
28+
Animal.haha();
29+
printan.describe();
30+
an._Animal__secret();# 访问私有变量
31+
printAnimal.typeName,an.name,an.typeName;# animal Nacy animal
32+
an.typeName='change';
33+
printAnimal.typeName,an.typeName;# animal, change
34+
35+
# python 支持多继承
36+
classCat(Animal):# 继承,python不会主动的调父类的构造函数
37+
"""docstring for Cat"""
38+
def__init__(self,name):
39+
Animal.__init__(self,name,'喵喵喵喵');
40+
41+
cat=Cat('Xiao hua');
42+
printcat.describe();
43+
44+

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp