Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit a7a59bf

Browse files
committed
class tutorial
1 parent e2e8de5 commit a7a59bf

File tree

1 file changed

+106
-0
lines changed

1 file changed

+106
-0
lines changed

python/tutorial3_5/t7_class.py

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
# 类
2+
3+
# 一个定义于某模块中的函数的全局作用域是该模块的命名空间,而不是该函数的别名被定义或调用的位置
4+
# global 语句用以指明某个特定的变量为全局作用域,并重新绑定它。nonlocal 语句用以指明某个特定的变量为封闭作用域,并重新绑定它。
5+
6+
7+
def scope_test():
8+
def do_local():
9+
spam = 'local spam'
10+
11+
def do_nonlocal():
12+
nonlocal spam
13+
spam = 'nonlocal spam'
14+
15+
def do_global():
16+
global spam
17+
spam = 'global spam'
18+
spam = 'test spam'
19+
do_local()
20+
print('After local assignment: {0}' . format(spam)) # After local assignment: test spam
21+
do_nonlocal()
22+
print('After nonlocal assignment: {0}' . format(spam)) # After nonlocal assignment: nonlocal spam
23+
do_global()
24+
print('After global assignment: {0}' . format(spam)) # After global assignment: nonlocal spam
25+
26+
scope_test()
27+
print('In global scope: {0}' . format(spam)) # In global scope: global spam
28+
29+
# 方法对象 & 函数对象
30+
# 通常,以 n 个参数的列表去调用一个方法就相当于将方法的对象插入到参数列表的最前面后,以这个列表去调用相应的函数。
31+
# 以一个参数列表调用方法对象时,它被重新拆封,用实例对象和原始的参数列表构造一个新的参数列表,然后函数对象调用这个新的参数列表。
32+
# 实例变量用于对每一个实例都是唯一的数据,类变量用于类的所有实例共享的属性和方法。
33+
34+
# 类对象,支持两种操作:属性引用和实例化
35+
36+
37+
class Complex:
38+
"""
39+
a simple class example
40+
"""
41+
r = ''
42+
i = ''
43+
44+
def __init__(self, realpart, imagpart):
45+
self.r = realpart
46+
self.i = imagpart
47+
48+
x = Complex(3, 4)
49+
print('The value of r, i is {0}, {1},and doc string is {docStr}' . format(x.r, x.i, docStr=x.__doc__))
50+
51+
# 一般,方法的第一个参数被命名为 self,并且可以通过 self 参数调用其它的方法
52+
53+
54+
class Bag:
55+
56+
data = []
57+
58+
def __init__(self):
59+
self.data = []
60+
61+
def add(self, x):
62+
self.data.append(x)
63+
return self
64+
65+
def add_twice(self, x):
66+
self.add(x)
67+
self.add(x)
68+
69+
x = Bag()
70+
x.add(1)
71+
x.add_twice(2)
72+
print(x.data, Bag.data) # [1, 2, 2] []
73+
74+
# 继承
75+
# python 有两个用于继承的函数:
76+
# 函数 isinstance() 用于检查实例类型:isinstance(obj, int) 只有在 obj.__class__ 是 int 或者其他从 int 继承的类型
77+
# 函数 issubclass() 用于检查类继承:issubclass(bool, int) 为 true,因为 boll 是 int 的子类
78+
79+
80+
class Egg(Bag):
81+
82+
def __init__(self):
83+
Bag.__init__(self)
84+
85+
86+
s = Egg()
87+
s.add_twice(3)
88+
print(s.data) # [3, 3]
89+
90+
# 多继承
91+
# python 同样支持多继承的形式,属性的搜索是从父类继承的深度优先,从左向右
92+
93+
94+
class MultiExtend(Complex, Bag):
95+
96+
def f(self):
97+
print('This is test')
98+
99+
100+
101+
102+
103+
104+
105+
106+

0 commit comments

Comments
 (0)