面向对象,看似不难。有的同学学过之后,还是不知道如何去使用它。有时候编写代码,写着写着就遇到坑了,比如写着写着就连你自己也在怀疑到底是不是面向对象编程了。
因此,本人想了一个比较简单的例子,来用面向对象的方式去思考它,去编码。那么,我不会做过多的说明,我想我的代码应该是最容易让人看懂的!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
#coding:utf-8
class
OS:
#描述操作系统对象
def
__init__(
self
, os_name):
self
.os_name
=
os_name
def
start_install(
self
):
print
(
"start install os:{0}"
.
format
(
self
.os_name))
class
Host:
#描述主机对象
def
__init__(
self
, host_id, brand, cpu, ram, disk):
self
.host_id
=
host_id
self
.brand
=
brand
self
.cpu
=
cpu
self
.ram
=
ram
self
.disk
=
disk
self
.os_type
=
None
def
power_off(
self
):
print
(
"host id:{0} Shutdown.."
.
format
(
self
.host_id))
def
power_on(
self
):
print
(
"host id:{0} Boot.."
.
format
(
self
.host_id))
def
install_os(
self
, os_name):
#服务器(host)可以安装操作系统
os
=
OS(os_name)
os.start_install()
self
.os_type
=
os.os_name
class
DataCenter:
#描述数据中心对象
def
__init__(
self
):
self
.hosts_list
=
[]
def
add_host(
self
, host_id, brand, cpu, ram, disk):
#数据中心里可以添加服务器(host)
host
=
Host(host_id, brand, cpu, ram, disk)
self
.hosts_list.append(host)
def
search_host(
self
, host_id):
for
host
in
self
.hosts_list:
if
host.host_id
=
=
host_id:
return
host
return
False
if
__name__
=
=
'__main__'
:
dc
=
DataCenter()
dc.add_host(
201
,
"IBM"
,
"16个"
,
"128GB"
,
"9TB"
)
host
=
dc.hosts_list[
0
]
print
(host.host_id, host.brand, host.cpu, host.ram, host.disk )
print
(host.os_type)
host.install_os(
"ubuntu14.04"
)
print
(host.os_type)
host.power_on()
host.power_off()
search_host_ret
=
dc.search_host(
201
)
print
(search_host_ret.disk)
|
其实你可以这样思考:
1、一个数据中心机房,可以有服务器,那么数据中心可以添加服务器,因此,描述数据中心对象的类可以有一个添加服务器的方法
2、那么,一台服务器可以有品牌,CPU,内存等等,那么描述服务器对象的类,应该有这些属性,并且,服务器还可以安装操作系统,那么应该也给他设计一个安装操作系统的方法
3、既然,服务器可以安装操作系统,那么在我的设计里,我把操作系统也看成了一个对象,描述操作系统对象的类中有操作系统名称,以及一个具体的安装方法
最后,对于那些还比较茫然的同学看了此文之后,会不会有点启发呢?我这里的例子只是起到一个抛砖引玉的作用,水平有限,还望广大python爱好者批评并指出。非常感谢!
本文转自 TtrToby 51CTO博客,原文链接:http://blog.51cto.com/freshair/2063228